python - Pandas :根据多级首次出现合并数据框

标签 python pandas merge

我正在尝试根据一对条件(monthnum)的第一次出现将一个大数据帧与一个小数据帧合并。

我拼凑了可行的代码(实际/期望的输出在底部),但它似乎可以更有效率。

我的问题是 - 我是否错过了一种更简单的方法来做到这一点?

设置:

import pandas as pd

m = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2]
n = [1,1,1,20,20,300,300,20,20,1,1,1,20,300,20,1,1,1,20,20,300,300,300,20,20,1,1]
df = pd.DataFrame({'month':m, 'num':n, 'x':0})

m2 = [1,1,1,2,2,2]
n2 = [1,20,300,1,20,300]
s2 = [11,222,3333,44,555,6666]
df2 = pd.DataFrame({'month':m2, 'num':n2, 'sum':s2})

当前代码:

dfx = pd.DataFrame(df.groupby(['month','num'])['x'].idxmax())
dfx.rename(columns = {'x':'find'}, inplace = True)

df2.set_index(['month','num'], inplace = True)
df2 = pd.merge(df2, dfx, left_index = True, right_index = True)

df = df.merge(df2, left_index = True, right_on = 'find', how = 'left')
df = df.drop(['find','x'], axis = 1).reset_index(drop = True).fillna(0)

输出:

    month  num     sum
0       1    1    11.0
1       1    1     0.0
2       1    1     0.0
3       1   20   222.0
4       1   20     0.0
5       1  300  3333.0
6       1  300     0.0
7       1   20     0.0
8       1   20     0.0
9       1    1     0.0
10      1    1     0.0
11      1    1     0.0
12      1   20     0.0
13      1  300     0.0
14      1   20     0.0
15      1    1     0.0
16      2    1    44.0
17      2    1     0.0
18      2   20   555.0
19      2   20     0.0
20      2  300  6666.0
21      2  300     0.0
22      2  300     0.0
23      2   20     0.0
24      2   20     0.0
25      2    1     0.0
26      2    1     0.0

最佳答案

如果我没理解错的话,你可以做一个常规的merge在你的两个 DataFrame 之间,然后合并 locduplicated将非第一次出现的事件归零:

df3 = df.merge(df2, how='left', on=['month', 'num'])
df3.loc[df3.duplicated(subset=['month', 'num']), 'sum'] = 0

结果输出:

   month  num   sum
0       1    1    11
1       1    1     0
2       1    1     0
3       1   20   222
4       1   20     0
5       1  300  3333
6       1  300     0
7       1   20     0
8       1   20     0
9       1    1     0
10      1    1     0
11      1    1     0
12      1   20     0
13      1  300     0
14      1   20     0
15      1    1     0
16      2    1    44
17      2    1     0
18      2   20   555
19      2   20     0
20      2  300  6666
21      2  300     0
22      2  300     0
23      2   20     0
24      2   20     0
25      2    1     0
26      2    1     0

关于python - Pandas :根据多级首次出现合并数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43946864/

相关文章:

python-3.x - Pandas 混合类型到整数

python - 检查数据框列中的所有值是否相同

scripting - 在 ClearCase 中查找指向某个版本的合并箭头

python - Pandas:根据列数据合并或连接数据框?

python - 如何使用单元测试在 Python 的单个测试套件中运行多个类?

python gflags 模块帮助标志不起作用

python - curl -u 和 python 请求之间有区别吗

python - 在 Python 中将字符串组合到数据框中的列表

python - 在 python 中查找重叠或插入的行

git - 有没有办法防止两个分支在git中 merge