【问题标题】:How to create new column in DataFrame based on other columns in Python Pandas? [duplicate]如何根据 Python Pandas 中的其他列在 DataFrame 中创建新列? [复制]
【发布时间】:2021-03-20 23:01:17
【问题描述】:

我有如下数据框:

data = pd.DataFrame({"col1" : ["a", "b", "c"], 
                     "binary" : [0, 1, 0]})

我想在这个名为"new"DataFrame 中创建并添加新列,如果在"binary" 列中为1,那么我想在我创建的列"new" 中获取来自"col1" 的数据,但如果在"binary" 列中为 0,那么我想要np.NaN。以下是我根据上面的描述和 DatFrame 真正需要的结果。

【问题讨论】:

  • 很多方法可以正确地做到这一点,import numpy as np;df['new'] = np.where(df['binary'].eq(1), df['col1'],np.nan)

标签: python pandas


【解决方案1】:

您可以使用 numpy 包中的 where 和 , 并执行以下操作:

import pandas as pd
import numpy as np
df = pd.DataFrame({"col1" : ["a", "b", "c"], "binary" : [0, 1, 0]})
df['new'] = np.where(df['binary']==1,df['col1'],np.nan)

prints:

print(df)
  col1  binary  new
0    a       0  NaN
1    b       1    b
2    c       0  NaN

【讨论】:

  • 在你的代码之后我有这个错误:TypeError: invalid type Promotion
  • import pandas as pd了吗?如上所示,它在我的身上运行顺利。
  • 好的我已经知道了,这是我的专栏的数据类型错误,谢谢!我选择你的答案为最佳
猜你喜欢
  • 2020-04-25
  • 1970-01-01
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
  • 2021-04-29
  • 2020-12-05
  • 1970-01-01
  • 2021-12-30
相关资源
最近更新 更多