gpt4 book ai didi

python-3.x - 根据特定条件合并 Pandas 数据框

转载 作者:行者123 更新时间:2023-12-04 03:27:50 25 4
gpt4 key购买 nike

我有一个如下所示的df

df1:

ID   Job   Salary
1 A 100
2 B 200
3 B 20
4 C 150
5 A 500
6 A 600
7 A 200
8 B 150

df2:

    ID      Type        Status       Age
1 2 P 23
2 1 P 28
8 1 F 33
4 3 P 48
14 1 F 23
11 2 P 28
16 2 F 23
41 3 P 38

df3:

ID   T_Type       Amount
1 K 20
2 L -50
1 K 30
3 K 5
1 K 100
2 L -50
1 L -30
25 K 500
1 K 20
4 L -80
19 K 30
2 K -5

数据说明

ID is the primary key of df1.

ID is the primary key of df2.

df3 does not have any primary key.

从上面,我想准备下面的dfs。

1. IDs which are in df1 and df2.

Expected output1:

ID Job Salary
1 A 100
2 B 200
4 C 150
8 B 150
  1. df1 中有而 df2 中没有的 ID

输出2:

ID   Job   Salary
3 B 20
5 A 500
6 A 600
7 A 200
  1. df1 和 df3 中的 ID

输出3:

ID   Job   Salary
1 A 100
2 B 200
3 B 20
4 C 150

4. IDs which are there in df1 and not in df3.

输出4:

ID   Job   Salary
5 A 500
6 A 600
7 A 200
8 B 150

最佳答案

>>> # 1. IDs which are in df1 and df2.
>>> df1[df1['ID'].isin(df2['ID'])]
ID Job Salary
0 1 A 100
1 2 B 200
3 4 C 150
7 8 B 150

>>> # 2. IDs which are there in df1 and not in df2
>>> df1[~df1['ID'].isin(df2['ID'])]
ID Job Salary
2 3 B 20
4 5 A 500
5 6 A 600
6 7 A 200

>>> # 3. IDs which are there in df1 and df3
>>> df1[df1['ID'].isin(df3['ID'])]
ID Job Salary
0 1 A 100
1 2 B 200
2 3 B 20
3 4 C 150

>>> # 4. IDs which are there in df1 and not in df3.
>>> df1[~df1['ID'].isin(df3['ID'])]
ID Job Salary
4 5 A 500
5 6 A 600
6 7 A 200
7 8 B 150

关于python-3.x - 根据特定条件合并 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67300254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com