[英]How to apply a function to a dataframe row based on a condition and values of another row?
[英]apply() a function on dataframe based on condition
在下面的函數中, myfun
首先檢查是否滿足特定條件,然后繼續操作。
此檢查在函數內部進行。
在應用該功能之前,是否可以進行檢查?
例如, if [column] == xyx, .apply(myfun)
下面的一些代碼:
import pandas as pd
x = pd.DataFrame({'col1':['hi','hello','hi','hello'],
'col2':['random', 'words', 'in', 'here']})
print(x)
col1 col2
0 hi random
1 hello words
2 hi in
3 hello here
我的函數檢查row['col1'] == 'hi'
並返回字符串success
else np.nan
。
def myfun(row):
# if this row contains string 'hi'
if row['col1'] == 'hi':
return 'success'
# otherwise return nan
else:
return pd.np.nan
# applying the function
x['result'] = x.apply(myfun,axis=1)
# result
col1 col2 result
0 hi random success
1 hello words NaN
2 hi in success
3 hello here NaN
是否可以僅將函數應用到col1
== 'hi'
那些行,而不是在apply()
函數內部執行該功能?
注意:我更喜歡使用apply()
的解決方案。 我知道還有其他選擇,例如np.where
。
是的,您可以,而且比apply
更好,像這樣。
由於apply
的每一行上環和loc
是一個量化的方法。 即使套用真的很強大,我也會盡量避免套用
x.loc[x['col1']=='hi', 'result'] = 'success'
這是根據條件使用apply()
方法。 我現在可以從函數中刪除條件檢查:
def myfun(row):
return 'success'
# applying the function based on condition
x['result'] = x[x['col1']=='hi'].apply(myfun,axis=1)
我也可以先創建一個蒙版。
mask = (x['col1']=='hi')
# applying the function based on condition
x['result'] = x[mask].apply(myfun,axis=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.