python 已弃用 pd.convert_objects(convert_numeric=True) 有效,替代方案出现故障

标签 python pandas dataframe

抛出以下警告,但我得到了实际的预期结果,当我尝试更改代码时,它失败了。

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 中的列。 ,然后通过fillna0最后将所有值转换为 ints 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/

相关文章:

python - 如何按元素移动数据帧以填充 NaN?

r - 使用自定义公式添加上一年和上一季度的销售额

python - PyQt 每 5 秒更新一次文本框

python - 异步 I/O 多路复用(套接字和线程间)

python - 在 csv 文件中查找字符串时提取行

python - 如何为 pd.util.testing.makeDataFrame() 设置随机种子?

python - 正则表达式删除Python中字符串中的下划线后跟数字?

python - 如何将参数作为附加参数传递给 python greenlet

python - 在 Pandas 中旋转 DataFrame 以输出到 CSV

r - 根据 R 中的条件向数据框添加多个新列