簡體   English   中英

為什么 lambda 函數不適用於 pandas

[英]Why lambda function does not apply in pandas

我正在使用圖片中描述的這個數據框: 在此處輸入圖像描述

我想在 Date 列中填寫 nan 值並編寫了以下代碼:

df['Date']=df['Date'].apply(lambda d: '1' if d==np.nan else d)

但這對我不起作用。 我完全糊塗了。

嘗試以這 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.

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