【问题标题】:Is there a way to cast data type of object to number in python 3有没有办法在python 3中将对象的数据类型转换为数字
【发布时间】:2020-09-13 20:16:45
【问题描述】:

我有一个包含大约 20 列的数据框。有一列名为结果,数据类型是对象,它包含诸如“死亡”和“活着”之类的值。我想计算输入和这个结果数据之间的相关性。我使用 Python3。我已经导入了 pandas 和 numpy。我想将“死亡”转换为 1,将“活着”转换为 0,因此我可以计算年龄与此结果之间的相关性。 有没有办法这样做? 提前致谢

【问题讨论】:

  • df['col_name'] = df['col_name'].eq('death').astype(int).
  • 谢谢,但它没有用。我正在使用 jupyter 笔记本。 pandas 无法处理它 pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas_libs\hashtable_class_helper.pxi 在 pandas._libs 中。 hashtable.PyObjectHashTable.get_item() pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

标签: python pandas numpy type-conversion correlation


【解决方案1】:

试试map:

df.outcomes.map({'death': 1, 'alive': 0})

这将返回一个带有数值的系列。

【讨论】:

  • 谢谢,但它没有用。 Pandas 将数据转换为 NaN,现在数据类型为 float64
猜你喜欢
  • 1970-01-01
  • 2022-06-18
  • 2021-07-10
  • 1970-01-01
  • 2022-06-15
  • 2017-09-26
  • 2021-05-17
  • 2020-09-12
  • 2011-04-07
相关资源
最近更新 更多