![](/img/trans.png)
[英]Pandas/Python: How to create new column based on values from other columns and apply extra condition to this new column
[英]How can I modify apply and lambda function to create new column based on other in Python Pandas?
我在 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 中做到這一點?
嘗試:
data["col2"] = data.apply(lambda x: 1 if x.col1 in [np.nan] else 0, axis = 1)
這應該有效,而您的則無效,因為它是np.nan.= np.nan
的功能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.