如何修改 apply 和 lambda 函数以基于 Python Pandas 中的其他列创建新列?
How can I modify apply and lambda function to create new column based on other in Python Pandas?
我在 Python Pandas 中有 table 数据类型为 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 中做到这一点?
尝试:
data["col2"] = data.apply(lambda x: 1 if x.col1 in [np.nan] else 0, axis = 1)
这应该有效,而你的无效,因为 a feature np.nan != np.nan
我在 Python Pandas 中有 table 数据类型为 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 中做到这一点?
尝试:
data["col2"] = data.apply(lambda x: 1 if x.col1 in [np.nan] else 0, axis = 1)
这应该有效,而你的无效,因为 a feature np.nan != np.nan