pandas - pandas groupby 应用优化循环
问题描述
对于以下数据:
index bond stock investor_bond inverstor_stock
0 1 2 A B
1 1 2 A E
2 1 2 A F
3 1 2 B B
4 1 2 B E
5 1 2 B F
6 1 3 A A
7 1 3 A E
8 1 3 A G
9 1 3 B A
10 1 3 B E
11 1 3 B G
12 2 4 C F
13 2 4 C A
14 2 4 C C
15 2 5 B E
16 2 5 B B
17 2 5 B H
bond1 有两个投资者 A,B。stock2 有三个投资者,B、E、F。对于每个投资者对(investor_bond,investor_stock),如果他们曾经投资过相同的债券/股票,我们希望将其过滤掉。
例如,对于 index=5 的一对 (B,F),我们想将其过滤掉,因为他们都投资了股票 2。
示例输出应如下所示:
index bond stock investor_bond investor_stock
11 1 3 B G
到目前为止,我已经尝试使用两个循环。
A1 = A1.groupby('bond').apply(lambda x: x[~x.investor_stock.isin(x.bond)]).reset_index(drop=True)
stock_list=A1.groupby(['bond','stock']).apply(lambda x: x.investor_stock.unique()).reset_index()
stock_list=stock_list.rename(columns={0:'s'})
stock_list=stock_list.groupby('bond').apply(lambda x: list(x.s)).reset_index()
stock_list=stock_list.rename(columns={0:'s'})
A1=pd.merge(A1,stock_list,on='bond',how='left')
A1['in_out']=False
for j in range(0,len(A1)):
for i in range (0,len(A1.s[j])):
A1['in_out'] = A1.in_out | (
A1.investor_bond.isin(A1.s[j][i]) & A1.investor_stock.isin(A1.s[j][i]))
print(j)
由于数据大小,循环永远运行,我正在寻找一种更快的方法。
解决方案
推荐阅读
- java - Installing apache-maven-3.5.4-bin.zip (can't set file paths properly)
- python - Unable to pip install pandas due to requirements
- php - Font Awesome 5 treatment of embedded icons in form input fields - Formatting is off vs V4.7
- dns - How to properly change DNS without changing emails?
- r - Maximums within Portions of a Matrix in R
- javascript - How to attach multiple callbacks to an YouTube API event
- apache-spark - Hadoop 文件格式
- python - 当 nan 序列连续 > 20 时删除数组的一部分
- html - 使用 rvest 获取 Whole Foods 商店列表
- java - 如何正确地将我的语法从字符串转换为数组