【问题标题】:How can I convert a column with values like [1] (objects) to a numeric value?如何将具有 [1] (对象)等值的列转换为数值?
【发布时间】:2020-10-20 15:01:40
【问题描述】:

我想将以下列(DataFrame 的一部分)转换为数值。

df = pd.DataFrame({ "Cluster": [[0], [1], [0], [2]]})

我的以下代码不起作用:

pd['Cluster_numeric'] = pd.to_numeric(df['Cluster'], errors='coerce')

【问题讨论】:

  • 试试df['Cluster_numeric'] = df['Cluster'].str[0]
  • 列表中可能有多个 int 吗?
  • 不,每行只有一个

标签: python pandas dataframe numeric


【解决方案1】:

考虑到您的列表长度始终为 1,这应该可以工作

df['Cluster_numeric']=df['Cluster'].apply(lambda x: x[0])

【讨论】:

  • int 此处不需要,您可以选择第一个元素。
  • df['Culster'].explode() 会更通用。
  • df['Culster'].explode() 也是一个对象
猜你喜欢
  • 2017-09-23
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
相关资源
最近更新 更多