我需要使用 True / False 值創建新列。如果基于其他列滿足條件,則在與 acc_no 關聯的每一行中都應該是 True。
原始 df:
trans_id acc_no trans_amount
1 123 15
2 456 10
3 123 50
4 456 60
5 789 35
6 123 20
7 789 18
8 456 73
9 789 37
僅 123 acc_no 的輸出應為 True:
trans_id acc_no trans_amount ANY_50$_TRANSACTION ?
1 123 15 True
2 456 10 False
3 123 50 True
4 456 60 False
5 789 35 False
6 123 20 True
7 789 18 False
8 456 73 False
9 789 37 False
我的代碼:
any_50$_transaction = []
for i in df["acc_no"].unique():
for ind in df[df["acc_no"] == i].index:
any_50$_transaction.append(np.where(df['trans_amount'][ind] == 50, True, False).any())
df["ANY_50$_TRANSACTION ?"] = any_50$_transaction
df
到目前為止,我的輸出是:
trans_id acc_no trans_amount ANY_50$_TRANSACTION ?
1 123 15 False
2 456 10 False
3 123 50 True
4 456 60 False
5 789 35 False
6 123 20 False
7 789 18 False
8 456 73 False
9 789 37 False
uj5u.com熱心網友回復:
按條件Series.isin過濾使用acc_no:
df['ANY_50$_TRANSACTION'] = df['acc_no'].isin(df.loc[df['trans_amount'].eq(50), 'acc_no'])
或GroupBy.transform與GroupBy.any:
df['ANY_50$_TRANSACTION'] = df['trans_amount'].eq(50).groupby(df['acc_no']).transform('any')
print (df)
trans_id acc_no trans_amount ANY_50$_TRANSACTION
0 1 123 15 True
1 2 456 10 False
2 3 123 50 True
3 4 456 60 False
4 5 789 35 False
5 6 123 20 True
6 7 789 18 False
7 8 456 73 False
8 9 789 37 False
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/388290.html
上一篇:從陣列中分配一個鍵名
