抛出以下警告,但我得到了实际的预期结果,当我尝试更改代码时,它失败了。
new_table = new_table.convert_objects(convert_numeric=True)
new_table=new_table.replace(np.nan,0) # This is used to make - to 0 for calc
警告(来自警告模块): new_table = new_table.convert_objects(convert_numeric=True) FutureWarning:convert_objects 已弃用。使用特定于数据类型的转换器 pd.to_datetime、pd.to_timedelta 和 pd.to_numeric。
new_table只不过是它包含的pandas数据框
A B C D E
1 - 3 5 6
2 3 5 6 7
- - 5 5 5
5 4 - - -
- - 4 - 4
9 - - 10 23
在这个给定的数据帧格式中,因为我们有字符串“-”,如果我使用下面的方法,进一步的求和或比较或乘法逻辑会抛出错误。
new_table = pd.to_numeric(new_table)
#new_table=new_table.replace("-",0)
new_table=new_table.replace(np.nan,0)
回溯(最近一次调用最后一次): 文件第 107 行,位于 new_table = pd.to_numeric(new_table) 文件第 113 行,位于 to_numeric 中 raise TypeError('arg 必须是列表、元组、一维数组或系列') 类型错误:arg 必须是列表、元组、一维数组或系列
处理这种情况的最佳方法是什么?第一行应该是 str 格式的索引,其他行是数字,这样我的算术计算就不会受到影响。
有什么帮助吗?
最佳答案
如果需要,您可以将所有非数值替换为 NaN
,使用 apply
使用函数 to_numeric
处理 df
中的列。 ,然后通过fillna
到0
最后将所有值转换为 int
s astype
:
new_table1 = new_table.apply(pd.to_numeric, errors='coerce').fillna(0).astype(int)
print (new_table1)
A B C D E
0 1 0 3 5 6
1 2 3 5 6 7
2 0 0 5 5 5
3 5 4 0 0 0
4 0 0 4 0 4
5 9 0 0 10 23
print (new_table1.dtypes)
A int32
B int32
C int32
D int32
E int32
dtype: object
如果所有值都是整数,另一个解决方案是 replace
所有非数字 + astype
:
new_table2 = new_table.replace('\D+', 0, regex=True).astype(int)
print (new_table2)
A B C D E
0 1 0 3 5 6
1 2 3 5 6 7
2 0 0 5 5 5
3 5 4 0 0 0
4 0 0 4 0 4
5 9 0 0 10 23
print (new_table2.dtypes)
A int32
B int32
C int32
D int32
E int32
dtype: object
如果所有值都只是 -
那么解决方案就很简单:
new_table3 = new_table.replace('-', 0, regex=True).astype(int)
print (new_table3)
A B C D E
0 1 0 3 5 6
1 2 3 5 6 7
2 0 0 5 5 5
3 5 4 0 0 0
4 0 0 4 0 4
5 9 0 0 10 23
print (new_table3.dtypes)
A int32
B int32
C int32
D int32
E int32
dtype: object
关于python 已弃用 pd.convert_objects(convert_numeric=True) 有效,替代方案出现故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48111638/