![](/img/trans.png)
[英]Create a new derived column in pandas if value inside the column is non-null
[英]Pandas create a new column based on non-null value of another column
我有一個數據框,我想根據值不為null的現有列創建一個新列。
現有列為小數,某些行為null。 我想用整數創建一個新列。
我正在使用lambda,但一直收到語法錯誤。 誰能告訴我怎么了? 謝謝
df['new'] = df['old'].apply(lambda x: int(x) if x>=0)
我也嘗試過:
df['new'] = df['old'].apply(lambda x: int(x) if x.isnull == False)
還有這個:
df['new'] = df['old'].apply(lambda x: x.astype(int) if x>=0)
語法錯誤指向最后一個右括號。
df['new'] = df['old'].apply(lambda x: int(x) if x>=0)
您需要在三元運算符的末尾添加一個else
。
df['new'] = df['old'].apply(lambda x: int(x) if x>=0 else 'Nope')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.