合并包含极值的数据帧

问题描述 投票:-2回答:2

我有2个数据帧,df1和df2:

df1
Out[66]: 
    A   B
0   1  11
1   1   2
2   1  32
3   1  42
4   1  54
5   1  66
6   2  16
7   2  23
8   3  13
9   3  24
10  3  35
11  3  46
12  3  51
13  4  12
14  4  28
15  4  39
16  4  49

df2
Out[80]: 
    B
0  32
1  42
2  13
3  24
4  35
5  39
6  49

我想合并数据帧,但同时包括A列中集合的第一个和/或最后一个值。这是所需结果的示例:

df3
Out[93]: 
    A   B
0   1   2
1   1  32
2   1  42
3   1  54
4   3  13
5   3  24
6   3  35
7   3  46
8   4  28
9   4  39
10  4  49

我正在尝试使用merge,但这只是切片重合的数据帧部分。有人有想法解决这个问题吗?谢谢!

python pandas dataframe merge
2个回答
3
投票

这是使用merge与指标,groupbyrolling做到这一点的一种方法:

df[df.merge(df2, on='B', how='left', indicator='Ind').eval('Found=Ind == "both"')
     .groupby('A')['Found']
     .apply(lambda x: x.rolling(3, center=True, min_periods=2).max()).astype(bool)]

输出:

    A   B
1   1   2
2   1  32
3   1  42
4   1  54
8   3  13
9   3  24
10  3  35
11  3  46
14  4  28
15  4  39
16  4  49

0
投票
 pd.concat([df1.groupby('A').min().reset_index(), pd.merge(df1,df2, on="B"), df1.groupby('A').max().reset_index()]).reset_index(drop=True).drop_duplicates().sort_values(['A','B'])
    A   B
0   1   2
4   1  32
5   1  42
1   2  16
2   3  13
7   3  24
8   3  35
3   4  12
9   4  39
10  4  49

打破每个部分

#Get Minimum
df1.groupby('A').min().reset_index()

# Merge on B
pd.merge(df1,df2, on="B")

# Get Maximum
df1.groupby('A').max().reset_index()

# Reset the Index and drop duplicated rows since there may be similarities between the Merge and Min/Max. Sort values by 'A' then by 'B'
.reset_index(drop=True).drop_duplicates().sort_values(['A','B'])
© www.soinside.com 2019 - 2024. All rights reserved.