![](/img/trans.png)
[英]How to create a new column based on calculation done with the existing column in Pandas?
[英]How to create a new column based on string match of existing column in pandas
我正在使用我的銀行交易數據將它們分成不同的類別。
這是我擁有的數據框 df:
Date Transaction Debit Credit Balance
13/12/21 ECOM PUR/ZOMATO/xxx 200 - 30000
13/12/21 UPI/P2M/xxx/SWIGGY/ 500 - 29500
14/12/21 NEFT/xxxxx/ - 30000 59500
我需要在事務列中搜索字符串匹配項並將它們存儲到新列中的類別中。
例如,SWIGGY 和 ZOMATO 被歸為食物,NEFT 被歸為工資
所需的 output:
Date Transaction Debit Credit Balance Categories
13/12/21 ECOM PUR/ZOMATO/xxx 200 - 30000 Food
13/12/21 UPI/P2M/xxx/SWIGGY/ 500 - 29500 Food
14/12/21 NEFT/xxxxx/ - 30000 59500 Salary
例如。 在 R 中,對於字符串匹配,我會使用類似
df[grepl('SWIGGY|ZOMATO', transactions)]$Categories <- 'Food'
我如何在 python 中對此進行 go? 對 python 真的很陌生,將不勝感激。 蒂亞:)
創建您的類別的字典映射,然后拆分您的Transaction
列並找到匹配項:
# Your categories here
categories = {'Food': ['SWIGGY', 'ZOMATO'],
'Salary': ['NEFT']}
# create a reverse dict of categories
mappings = {v: k for k, l in categories.items() for v in l}
df['Categories'] = df['Transaction'].str.split('/').explode().map(mappings).dropna()
Output:
>>> df
Date Transaction Debit Credit Balance Categories
0 13/12/21 ECOM PUR/ZOMATO/xxx 200 - 30000 Food
1 13/12/21 UPI/P2M/xxx/SWIGGY/ 500 - 29500 Food
2 14/12/21 NEFT/xxxxx/ - 30000 59500 Salary
>>> categories
{'Food': ['SWIGGY', 'ZOMATO'], 'Salary': ['NEFT']}
>>> mappings
{'SWIGGY': 'Food',
'ZOMATO': 'Food',
'NEFT': 'Salary'}
更新:如果您在一行上有多個匹配類別和/或沒有類別,您可以使用:
categories = {'Food': ['SWIGGY', 'ZOMATO'],
'Cream': ['ECOM PUR']}
mappings = {v: k for k, l in categories.items() for v in l}
df['Categories'] = \
df['Transaction'].str.split('/').explode().map(mappings).dropna() \
.groupby(level=0).apply(lambda x: ','.join(set(x))) \
.reindex(df.index).fillna('Other')
Output:
>>> df
Date Transaction Debit Credit Balance Categories
0 13/12/21 ECOM PUR/ZOMATO/xxx 200 - 30000 Cream,Food
1 13/12/21 UPI/P2M/xxx/SWIGGY/ 500 - 29500 Food
2 14/12/21 NEFT/xxxxx/ - 30000 59500 Other
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.