[英]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.