我有以下数据框:
为什么"sum"函数会有这种奇怪的行为?有没有办法阻止它将 "str" 转换回 "float"?谢谢你的帮助 :-)
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7],
'col_3': [14, 15, 16, 19]
})
我尝试将数字转换为字符串,然后将每行组合成一个字符串。
我可以使用以下方法实现:
df.apply(lambda x : ''.join(x.astype(str)),1)
Out[209]:
0 0414
1 1515
2 2616
3 3719
dtype: object# notice here dtype is object
这是问题
然后,我尝试使用sum
函数。
df.astype(str).sum(1)
Out[211]:
0 414.0
1 1515.0
2 2616.0
3 3719.0
dtype: float64
注意这里的 dtype
变成了 float
而不是 object
。
更多信息如下:
df.astype(str).applymap(type)
Out[221]:
col_1 col_2 col_3
0 <class 'str'> <class 'str'> <class 'str'>
1 <class 'str'> <class 'str'> <class 'str'>
2 <class 'str'> <class 'str'> <class 'str'>
3 <class 'str'> <class 'str'> <class 'str'>
为什么"sum"函数会有这种奇怪的行为?有没有办法阻止它将 "str" 转换回 "float"?谢谢你的帮助 :-)
try
except
让这个…… - BENY