我的熊貓資料框中有一堆零。我想用函式回傳的值替換它們。我正在使用fillna. 這是我的可重復性代碼的簡化版本:
import pandas as pd
import numpy as np
def replace(x):
v = x * 2
return v
df = pd.DataFrame({'col1': [1,np.nan,0],
'col2': [1,2,3]
})
df['col1'].replace(0, value returned by replace function)
理想情況下,我想使用 lambda 來做到這一點。這是我對 NaN 的處理方式:
df['col1'].fillna(df.apply(lambda x: replace(x.col2), axis=1), inplace=True)
uj5u.com熱心網友回復:
apply 可以采用您希望使用的 lambda 函式:
df['col1'] = df.apply(lambda x: x['col2']*2 if x['col1'] == 0 else x['col1'], axis=1)
uj5u.com熱心網友回復:
通常,如果要將 DataFrame 中的特定值替換為簡單函式回傳的值,可以使用pd.DataFrame.where()。
用以下結果替換 DataFrame 中的所有 0 replace():
new_df = df.where( df != 0, replace( df ) )
只要條件為真(在這種情況下,df 不等于 0),函式保持原來的值,只要條件為假(在這種情況下,df 等于 0),函式就回傳 的結果replace()。
where() 函式也可以應用于單個系列。要使用您的功能:
df["col1"] = df["col1"].where( df["col1"] != 0, replace( df["col1"] ) )
要替換的值col2與replace()其中col1等于零:
df["col2"] = df["col2"].where( df["col1"] != 0, replace( df["col2"] ) )
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/357503.html
