【问题标题】:python deprecated pd.convert_objects(convert_numeric=True) works the alternative one malfunctionspython deprecated pd.convert_objects(convert_numeric=True) 可以替代一个故障
【发布时间】:2018-01-09 21:00:35
【问题描述】:

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

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)

Traceback(最近一次调用最后一次): 文件第 107 行,在 new_table = pd.to_numeric(new_table) 文件第 113 行,在 to_numeric raise TypeError('arg 必须是列表、元组、一维数组或系列') TypeError: arg 必须是列表、元组、一维数组或系列

处理这种情况的最佳方法是什么,第一行应该是 str 格式的索引,其他行是数字,这样我的算术计算就不会受到影响。

有什么帮助吗?

【问题讨论】:

  • 那么我的解决方案如何运作?
  • 我会检查并反馈,谢谢!

标签: python pandas dataframe


【解决方案1】:

如果需要,您可以将所有非数值替换为 NaNs 使用 apply 处理 df 中的列,并使用函数 to_numeric,然后将 0 替换为 fillna,并将所有值最后替换为 @ 987654332@s by 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

【讨论】:

  • new_table1 = new_table.apply(pd.to_numeric, errors='coerce').fillna(0).astype(int) 这解决了我的逻辑问题,警告现在消失了。
  • 超级,很高兴能帮上忙!你在熊猫方面还是更好;)
  • python pandas 的逻辑非常好,学习了很多,它是一片海洋
  • 是的,我记得这些天,我也很惊讶;)
  • 天哪,如果索引为 Date 存在,则上面给出的解决方案也将其替换为 int,因此 Date 索引变为 0。如何避免这种情况。
猜你喜欢
  • 1970-01-01
  • 2016-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 2016-01-12
  • 2014-04-12
  • 1970-01-01
相关资源
最近更新 更多