繁体   English   中英

在 DataFrame 中查找

[英]Look up in DataFrame

我有一个数据框如下:

index    name      col1   col2     count

"there is some values"


col1 : is the index of a value in df
col2 : is the index of a value in df

我想在 col 1 和 col 2 中找到与索引相关的名称,并将它们放在匹配 1 和匹配 2 中。我想将当前索引和匹配索引的计数相加。 例如,对于第一行,我想将第一行和匹配行的计数相加。

我从昨天开始一直在尝试,但我无法产生结果。 谁能帮我?

我想要的是:


index     name       col1     col 2      count     match 1   match 2    sum
1          x1          5       3           2        x5         x3      2+7+2
2          x2          4       6           3        x4         x6       3+1+1
3          x3                              7       
4          x4                              1
5          x5                              2
6          x6                              1

如果我正确理解了这个问题,我相信这会让你到达那里:

df = pd.DataFrame([
        ['x1',      5,      3, 2, 'x5', 'x3'],
        ['x2',      4,      6, 3, 'x4', 'x6'],
        ['x3', np.nan, np.nan, 7,           ],
        ['x4', np.nan, np.nan, 1,           ],
        ['x5', np.nan, np.nan, 2,           ],
        ['x6', np.nan, np.nan, 1,           ],
    ], columns=['name', 'col1', 'col2', 'count', 'match1', 'match2'])
df2 = df.merge(df, how='inner', left_on='match1', right_on='name', suffixes=('', '_match1'))
df3 = df2.merge(df, how='inner', left_on='match2', right_on='name', suffixes=('', '_match2'))
df3['sum'] = df3['count'] + df3['count_match1'] + df3['count_match2']
df3 = df3[list(df.columns) + ['sum']]

>>> print(df3)
  name  col1  col2  count match1 match2  sum
0   x1   5.0   3.0      2     x5     x3   11
1   x2   4.0   6.0      3     x4     x6    5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM