![](/img/trans.png)
[英]updated question: Updating a row value based on another row value with certain condition, pandas
[英]Pandas - Updating value in row based on condition with .apply()
簡化,我想使用 function 來檢查一行的條件並相應地設置值:
def helper(row):
if row["A"] == "TEST":
row["B"] = "WOW"
else:
row["C"] = "NO_GO"
moddf = df.apply(helper, axis=1)
我可以使用 iterrows() 來做到這一點,但是.apply 應該更快地迭代 df 中的 1M 行。
您不需要(也不應該使用)申請:
# toy data
df = pd.DataFrame({'A':['TEST','NO'],
'B' : ['A','B'],
'C' :list('12')})
s = df['A']=='TEST'
df.loc[s,'B'] = 'WOW'
df.loc[~s, 'C'] = 'NO_GO'
Output:
A B C
0 TEST WOW 1
1 NO B NO_GO
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.