我有一张表,有将近3千1百万条记录。 大约有10列,其中两列是卡号和交易状态。每张卡可以有多行。因此,同一张卡可能有2000行,每行作为一个具有相应状态的交易
事务状态的值为“Y”/“N”。你知道吗
我想使用pandas dataframe将另外两列添加到此表中,“count\u of \u approved”、“count\u of \u rejected”。你知道吗
我该怎么做? trn公司 到目前为止,我一直在使用get\u dummies()和merge(),但是这需要很多时间,更糟糕的是,会导致内存不足错误。你知道吗
我的意见如下:
trn_id | card_id | status
1 | c1 | Y
2 | c2 | Y
3 | c2 | N
4 | c3 | Y
5 | c3 | Y
我希望我的输出是
trn_id | card_id | status | num_approved | num_of_denied
1 | c1 | Y | 1 | 0
2 | c2 | Y | 1 | 1
3 | c2 | N | 1 | 1
4 | c3 | Y | 2 | 0
5 | c3 | Y | 2 | 0
我的代码如下:
import pandas as panda
a = panda.DataFrame({'id':[1,2,3],'c_id':[22,22,33], 'status':['Y','Y','N']})
temp = a.status.str.get_dummies()
a[['N','Y']]= temp
tt = a.groupby(['c_id'])['Y'].count()
tt=tt.reset_index()
yes_count_added = a.merge(tt,how='right',on='c_id')
yes_count_added.rename(columns = {'Y_y':'num_of_approved'})
您可以^{} } 和lambda表达式} :
card_id
并使用^{sum
使用status
的次数等于Y
的num_approved
或N
的num_of_denied
的^{使用
str.get_dummies
+单个groupby
调用来提高性能:您可以使用crosstab:
输出
相关问题 更多 >
编程相关推荐