[英]Why lambda function does not apply in pandas
嘗試以這 3 種方式中的 1 種方式進行
為所有南
df.fillna('1', inplace=True)
對於特定的 col
df["Date"] = df["Date"].fillna('1')
df.Date = df.Date.fillna('1')
帶 lambda 函數
df['Date']=df['Date'].apply(lambda d: '1' if pd.isnull(d) else d)
要根據月或日列設置值,需要訪問這些列,以及當前空值所在的行。 這意味着您可能不想將 .apply 中的更改專門應用於“日期”列
相反,獲取該 col 的 na 掩碼,並根據該值將更改應用於“date” col
import pandas as pd
df = {
"Date": ["2020-02-12", None, "2020-04-12"],
"Month": ["Feb", "March", "April"]
}
df = pd.DataFrame(df)
print('df before set: \n',df)
# get na
date_is_null = (df["Date"].isna())
# apply dynamic value to null depending on value in another column
df.loc[date_is_null, 'Date']=df.loc[date_is_null, "Month"]
print('df after set: \n',df)
輸出
df before set:
Date Month
0 2020-02-12 Feb
1 None March
2 2020-04-12 April
df after set:
Date Month
0 2020-02-12 Feb
1 March March
2 2020-04-12 April
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.