Python 对数据帧中存在非数值的所有列求和
我有以下数据集:Python 对数据帧中存在非数值的所有列求和,python,pandas,ipython,Python,Pandas,Ipython,我有以下数据集: df = pd.DataFrame({'col1' : [12,3,4,5,'a',5], 'col2' : [1,5,'b',6,10,1]}) 如果我运行df.sum(axis=0,numeric_only=True),我会得到以下输出: Series([], dtype: float64) 但是,如果我将非数值更改为None,则它可以正常工作 因此,我的问题是,当存在非数值时,如何才能找到数据集中所有列的总和?我认为您可以使用应用,因为to_numeric仅适用于列(
df = pd.DataFrame({'col1' : [12,3,4,5,'a',5], 'col2' : [1,5,'b',6,10,1]})
如果我运行df.sum(axis=0,numeric_only=True),我会得到以下输出:
Series([], dtype: float64)
但是,如果我将非数值更改为None
,则它可以正常工作
因此,我的问题是,当存在非数值时,如何才能找到数据集中所有列的总和?我认为您可以使用应用,因为to_numeric
仅适用于列(Series
):
另一种解决方案是concat
和列表理解
:
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
如果只有几列更快,请重复代码:
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
我认为numeric\u 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
功夫熊猫耶兹雷尔:)谢谢,但假设我有一个包含大量列的df,我想通过编程实现这一点?第一个解决方案不起作用<代码>(df.apply(lambda x:pd.to_numeric(x,errors='concurve')).sum())
?
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