【问题标题】:How can I modify apply and lambda function to create new column based on other in Python Pandas?如何修改 apply 和 lambda 函数以基于 Python Pandas 中的其他列创建新列?
【发布时间】:2022-01-13 00:21:34
【问题描述】:

我在 Python Pandas 中有如下表,数据类型为 float64:

col1
--------
245.121
NaN
44.908

我尝试使用以下代码创建新列“col2”:

data["col2"] = data.apply(lambda x: 1 if x.col1== np.nan else 0, axis = 1)

不幸的是,当我使用上面的代码时,我到处都是 0,为什么?如何修改我的代码以实现如下所示:

col1      col2
--------
245.121  | 0
NaN      | 1
44.908   | 0

如何在 Python Pandas 中做到这一点?

【问题讨论】:

标签: python pandas dataframe lambda apply


【解决方案1】:

试试:

data["col2"] = data.apply(lambda x: 1 if x.col1 in [np.nan] else 0, axis = 1)

这应该有效,而您的无效,因为 a featurenp.nan != np.nan

【讨论】:

  • 不幸的是它仍然不起作用,嗯我不可能......我不明白为什么
  • 对不起,我在调试时使用了 df,现在它应该可以工作了
  • np.where(df.col1.isin([np.nan]), 1, 0)
猜你喜欢
  • 2021-12-30
  • 1970-01-01
  • 2016-02-10
  • 2017-04-17
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
相关资源
最近更新 更多