相关疑难解决方法(0)

Pandas数据帧总排

我有一个数据框,如:

     foo  bar  qux
0    a    1    3.14
1    b    3    2.72
2    c    2    1.62
3    d    9    1.41
4    e    3    0.58
Run Code Online (Sandbox Code Playgroud)

我想在数据帧的末尾添加一个"总"行:

     foo  bar  qux
0    a    1    3.14
1    b    3    2.72
2    c    2    1.62
3    d    9    1.41
4    e    3    0.58
5    tot  15   9.47
Run Code Online (Sandbox Code Playgroud)

我已经尝试使用该sum命令,但我最终得到了一个系列,虽然我可以转换回Dataframe,但不维护数据类型:

tot_row = pd.DataFrame(df.sum()).T
tot_row['foo'] = 'tot'
tot_row.dtypes:
     foo    object
     bar    object
     qux    object
Run Code Online (Sandbox Code Playgroud)

我想维护原始数据框中的数据类型,因为我需要将其他操作应用于总行,例如:

baz = 2*tot_row['qux'] + 3*tot_row['bar']
Run Code Online (Sandbox Code Playgroud)

python pandas

49
推荐指数
9
解决办法
6万
查看次数

标签 统计

pandas ×1

python ×1