[英]Apply a function with multiple arguments on an entire dataframe in Pandas
我在熊貓中有以下數據框:
df = pd.DataFrame({'field_1' : ['a', 'b', np.nan, 'a', 'c'], 'field_2': ['c', 'b', 'a', np.nan, 'c']}, index=[1,2,3,4,5])
我想在整個數據框中應用以下功能,以其他方式替換每個值。
例如:
def func_replace(value, n):
if value == 'a':
return 'This is a'*n
elif value == 'b':
return 'This is b'*n
elif value == 'c':
return 'This is c'*n
elif str(value) == 'nan':
return np.nan
else:
'The value is not included'
因此最終產品看起來像(假設n=1
)。
例如:
df = pd.DataFrame({'field_1' : ['This is a', 'This is b', np.nan, 'This is a', 'This is c'], 'field_2': ['This is c', 'This is b', 'This is a', np.nan, 'This is c']}, index=[1,2,3,4,5])
我嘗試了以下方法:
df.apply(func_replace, args=(1), axis=1)
和其他選項,但這總是給我一個錯誤。
我知道我可以編寫一個遍歷每一列的for
循環,並使用lambda函數來解決此問題,但是我覺得有一個更簡單的選擇。
我覺得該解決方案比我想象的要容易,但是我無法弄清楚正確的語法。
任何幫助將非常感激。
只需修改您的函數以在Series
中每個值的級別進行操作,然后使用applymap
。
df = pd.DataFrame({'field_1' : ['a', 'b', np.nan, 'a', 'c'], 'field_2': ['c', 'b', 'a', np.nan, 'c']}, index=[1,2,3,4,5])
df
Out[35]:
field_1 field_2
1 a c
2 b b
3 NaN a
4 a NaN
5 c c
現在,如果我們將函數定義為:
def func_replace(value):
if value == 'a':
return 'This is a'
elif value == 'b':
return 'This is b'
elif value == 'c':
return 'This is c'
elif str(value) == 'nan':
return np.nan
else:
'The value is not included'
在DataFrame
每個值上調用此函數非常簡單:
df.applymap(func_replace)
Out[42]:
field_1 field_2
1 This is a This is c
2 This is b This is b
3 NaN This is a
4 This is a NaN
5 This is c This is c
我認為您需要:
def func_replace(df, n):
df_temp = df.replace({r"[^abc]": "The value is not included"}, regex=True)
return df_temp.replace(["a", "b", "c"], ["This is a " * n, "This is b " * n, "This is c " * n])
df.apply(func_replace, args=(2,))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.