仅对 pandas 中的数字列求和 [英] Sum only numeric columns in pandas

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

问题描述

我有一个如下所示的 df,(前 2 行是文本,第一列是日期)

I have a df like below, (initial 2 rows are text and 1st column is date)

In [4]: df
Out[4]: 
           test          bs         dv         if          ir         md         qb         sy          tb
0       TESTacc      a10900     a10900     a10900    IJJMKK11     a10900     a10900     a10900      a10900
1   01-Feb-2019  18.8668013  4.6021207  0.9330807  13.9766832  2.9002571  0.2824343  0.8280988   0.8587644
2   04-Feb-2019   16.187526  3.1000162  0.4145835  14.6465183   2.848472  0.2516608  0.8618771    0.218063

我需要得到这个具有 3 位小数精度的 csv我还需要添加一个总计"列(最右边的列)我已经尝试了以下事情,但这些都不正确

I need to get have this csv with 3 decimal precision Also I need to add a "Total" Column (rightmost column) I have tried the below things, but these are not proper

要添加我所做的总列:

ndf=df.iloc[2:,1:] #take only numerics in ndf
ndf = ndf.apply(pd.to_numeric)
ndf=ndf.round(3)
df['total']=ndf.sum(axis=1)

这不是做简单的事情的正确方法,例如添加总计列

This is not a proper way of doing simple thing like adding a total column

所以我试过了df=df.apply(pd.to_numeric,errors='ignore')但圆形仍然不适用于 df我的目的是只添加一个总计列并将所有数字四舍五入到小数点后 3 位.附加:一旦完成,我将添加最后一行作为中值行,每列都有中值

So I tried df=df.apply(pd.to_numeric,errors='ignore') but round still wont work on df My intent is to just add a Total column and have all numbers rounded to 3 decimals. Additional: Once this is done I would add a last row as median row, having median for each column

推荐答案

根据 最新的 Pandas 文档 1.0.3 您只能使用以下代码对数字列求和:

According to the latest pandas documentation 1.0.3 you can sum only numeric columns with the following code:

df_sum = df.sum(numeric_only = True)

这将对 df 中的所有数字列求和并将其分配给变量 df_sum.

This will sum all numeric columns in df and assign it to variable df_sum.

这篇关于仅对 pandas 中的数字列求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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