将存在非数值的Pandas DataFrame中的所有列求和

cap*_*mar 3 python ipython pandas

我有以下数据集:

df = pd.DataFrame({'col1' : [12,3,4,5,'a',5], 'col2' : [1,5,'b',6,10,1]})
Run Code Online (Sandbox Code Playgroud)

如果运行df.sum(axis=0, numeric_only=True),则会得到以下输出:

Series([], dtype: float64)
Run Code Online (Sandbox Code Playgroud)

但是,如果我将非数字值更改为,None则可以正常工作。

因此,我的问题是,当存在非数值时,如何找到数据集中所有列的总和?

jez*_*ael 5

我认为您可以使用to_numericwith,apply因为它to_numeric仅适用于列(Series):

print (df.apply(pd.to_numeric, errors='coerce').sum())
#same as
#print (df.apply(lambda x: pd.to_numeric(x, errors='coerce')).sum())
col1    29.0
col2    23.0
dtype: float64
Run Code Online (Sandbox Code Playgroud)

另一种方案是concatlist comprehension

df = pd.concat([pd.to_numeric(df[col], errors='coerce') for col in df], axis=1).sum()
print (df)
col1    29.0
col2    23.0
dtype: float64
Run Code Online (Sandbox Code Playgroud)

如果只快几列,请重复代码:

df.col1 = pd.to_numeric(df.col1, errors='coerce')
df.col2 = pd.to_numeric(df.col2, errors='coerce')
print (df.sum())
col1    29.0
col2    23.0
dtype: float64
Run Code Online (Sandbox Code Playgroud)

我认为numeric_only=True不适用于混合内容的列-带字符串值的数字。

样本- col1是数字,col2不是数字:

df = pd.DataFrame({'col1' : [1,3,4], 'col2' : ['1','5','b']})
print (df)
   col1 col2
0     1    1
1     3    5
2     4    b

print (df.sum(numeric_only=True))
col1    8
dtype: int64
Run Code Online (Sandbox Code Playgroud)