【发布时间】:2018-08-30 23:55:34
【问题描述】:
我有一个与this question 类似的问题相似,但只是不同而已,无法用相同的解决方案解决...
我有两个数据框,df1 和 df2,如下所示:
import pandas as pd
import numpy as np
np.random.seed(42)
names = ['jack', 'jill', 'jane', 'joe', 'ben', 'beatrice']
df1 = pd.DataFrame({'ID_a':np.random.choice(names, 20), 'ID_b':np.random.choice(names,20)})
df2 = pd.DataFrame({'ID':names})
>>> df1
ID_a ID_b
0 joe ben
1 ben jack
2 jane joe
3 ben jill
4 ben beatrice
5 jill ben
6 jane joe
7 jane jack
8 jane jack
9 ben jane
10 joe jane
11 jane jill
12 beatrice joe
13 ben joe
14 jill beatrice
15 joe beatrice
16 beatrice beatrice
17 beatrice jane
18 jill joe
19 joe joe
>>> df2
ID
0 jack
1 jill
2 jane
3 joe
4 ben
5 beatrice
我想做的是在df2 中添加一列,其中 count 行在df1 中可以在 either 中找到给定的名称strong> 列ID_a 或ID_b,结果如下:
>>> df2
ID count
0 jack 3
1 jill 5
2 jane 8
3 joe 9
4 ben 7
5 beatrice 6
这个循环得到了我需要的东西,但对于大型数据帧效率低下,如果有人能提出一个替代的、更好的解决方案,我将非常感激:
df2['count'] = 0
for idx,row in df2.iterrows():
df2.loc[idx, 'count'] = len(df1[(df1.ID_a == row.ID) | (df1.ID_b == row.ID)])
提前致谢!
【问题讨论】:
-
我添加了更多选项。对@jpp 的时间持保留态度,当您对少数行的解决方案进行基准测试时,时间真的毫无意义。您可能想在更大的数据帧上尝试这些解决方案,然后您会真正看到不同之处。
-
我注意到了,我真的很感激。我的实际数据框显然比我发布的要大得多,但不是巨大,所以为了优雅,我可以承受一点效率的损失。然而,我原来的解决方案似乎既低效和不优雅,这就是为什么我想要一些输入...
标签: python string pandas numpy dataframe