在另一个数据框中计算pandas数据框的一行

3
我想在一个数据框中添加一列,该列包含另一个数据框中匹配项的计数。例如,
df1 = pd.DataFrame({'A':['yes','yes','yes','yes','yes','yes','no','no','no','no','no','no'],
                    'B':['L','L','M','M','H','H','L','L','M','M','H','H'],
                    'C':[True,False,True,False,True,False,True,False,True,False,True,False]})

对于df1中的每一行,我想知道它在df2中的计数

df2 = pd.DataFrame({'A':['yes','yes','no','yes','no','yes','yes','no','no','no'],
                   'B':['L','M','M','L','M','M','H','L','H','M'],
                   'C':[True,True,True,True,True,False,False,False,False,False]})

在df1中添加一列'count',期望输出如下:
index     A     B     C     count
0        yes    L   True        2
1        yes    L   False       0
2        yes    M   True        1
3        yes    M   False       1
4        yes    H   True        0
5        yes    H   False       1
6         no    L   True        0
7         no    L   False       1
8         no    M   True        2
9         no    M   False       1
10        no    H   True        0
11        no    H   False       1

请问有什么符合Python风格的方法来做这件事吗?谢谢提前。

1个回答

5
您可以尝试使用merge,将df2groupbysize一起使用。最后,您可以使用fillna,选择要替换为0的列来替换所有NaN值:
print df2.groupby(['A','B','C']).size().reset_index(name='count')
     A  B      C  count
0   no  H  False      1
1   no  L  False      1
2   no  M  False      1
3   no  M   True      2
4  yes  H  False      1
5  yes  L   True      2
6  yes  M  False      1
7  yes  M   True      1

print pd.merge(df1, 
               df2.groupby(['A','B','C']).size().reset_index(name='count'),
               on=['A','B','C'],
               how="left").fillna({'count': 0})

      A  B      C  count
0   yes  L   True      2
1   yes  L  False      0
2   yes  M   True      1
3   yes  M  False      1
4   yes  H   True      0
5   yes  H  False      1
6    no  L   True      0
7    no  L  False      1
8    no  M   True      2
9    no  M  False      1
10   no  H   True      0
11   no  H  False      1

我改进了答案,因为fillna(0)会在整个df中替换掉所有的NaN,而我们只需要在count列中替换掉NaN - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接