簡體   English   中英

熊貓根據另一列的非空值創建一個新列

[英]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')

您收到語法錯誤,因為您的lambda函數不正確。 具體來說, if ... else ... 條件表達式是錯誤的。 條件表達式必須為

conditional_expression ::=  or_test [“if” or_test “else” expression]

您缺少else部分。

我想提到的另一件事是,轉換數據類型的一種優美方法是使用astype函數 如果要在某種條件下投射數據,可以執行以下操作:

new = df.loc[df.old>0].astype('int')

然后new將成為您需要的系列。

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM