pandas 数据框总行 [英] Pandas dataframe total row

查看:79
本文介绍了 pandas 数据框总行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,类似:

I have a dataframe, something like:

     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

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

and I would like to add a 'total' row to the end of the dataframe:

     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

我尝试使用sum命令,但最终得到一个Series,尽管我可以将其转换回Dataframe,但是却不维护数据类型:

I've tried to use the sum command but I end up with a Series, which although I can convert back to a Dataframe, doesn't maintain the data types:

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

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

I would like to maintain the data types from the original data frame as I need to apply other operations to the total row, something like:

baz = 2*tot_row['qux'] + 3*tot_row['bar']

推荐答案

将总计行附加到

df.append(df.sum(numeric_only=True), ignore_index=True)

仅当您有一列字符串或对象时,才需要进行转换.

The conversion is necessary only if you have a column of strings or objects.

这是一个脆弱的解决方案,因此我建议仍然坚持对数据框进行操作.例如.

It's a bit of a fragile solution so I'd recommend sticking to operations on the dataframe, though. eg.

baz = 2*df['qux'].sum() + 3*df['bar'].sum()

这篇关于 pandas 数据框总行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆