pandas 合并数据帧不同的行数重复数据
pandas merge dataframes different line count repeat data
我有两个要合并的数据框(df1
和 df2
)。我想要 df1
中每一行的价格和代码。我怎样才能合并这些,以便价格和代码自行重复并根据水果排列?我认为我需要将水果设置为索引才能执行此操作?
df1 =
fruit grown farm
apple fruit ranch
banana fresh grow
grapes paradise lake
melon country hills
cherry paradise lake
orange paradise lake
apple fruit ranch
apple paradise lake
cherry fresh grow
grapes fruit ranch
apple country hills
melon paradise lake
cherry fruit ranch
orange fresh grow
df2 =
fruit price code
apple 3 568
banana 2 426
grapes 4 112
melon 6 368
cherry 1 569
orange 4 775
谢谢
您只需使用 pandas.DataFrame.merge
合并它们,但您可能希望先更改列名,然后才能合并它们。
df1.merge(df2.rename(columns={'fruit':'fruit grown'}), how='left')
输出:
fruit grown farm price code
0 apple fruit ranch 3 568
1 banana fresh grow 2 426
2 grapes paradise lake 4 112
3 melon country hills 6 368
4 cherry paradise lake 1 569
5 orange paradise lake 4 775
6 apple fruit ranch 3 568
7 apple paradise lake 3 568
8 cherry fresh grow 1 569
9 grapes fruit ranch 4 112
10 apple country hills 3 568
11 melon paradise lake 6 368
12 cherry fruit ranch 1 569
13 orange fresh grow 4 775
我有两个要合并的数据框(df1
和 df2
)。我想要 df1
中每一行的价格和代码。我怎样才能合并这些,以便价格和代码自行重复并根据水果排列?我认为我需要将水果设置为索引才能执行此操作?
df1 =
fruit grown farm
apple fruit ranch
banana fresh grow
grapes paradise lake
melon country hills
cherry paradise lake
orange paradise lake
apple fruit ranch
apple paradise lake
cherry fresh grow
grapes fruit ranch
apple country hills
melon paradise lake
cherry fruit ranch
orange fresh grow
df2 =
fruit price code
apple 3 568
banana 2 426
grapes 4 112
melon 6 368
cherry 1 569
orange 4 775
谢谢
您只需使用 pandas.DataFrame.merge
合并它们,但您可能希望先更改列名,然后才能合并它们。
df1.merge(df2.rename(columns={'fruit':'fruit grown'}), how='left')
输出:
fruit grown farm price code
0 apple fruit ranch 3 568
1 banana fresh grow 2 426
2 grapes paradise lake 4 112
3 melon country hills 6 368
4 cherry paradise lake 1 569
5 orange paradise lake 4 775
6 apple fruit ranch 3 568
7 apple paradise lake 3 568
8 cherry fresh grow 1 569
9 grapes fruit ranch 4 112
10 apple country hills 3 568
11 melon paradise lake 6 368
12 cherry fruit ranch 1 569
13 orange fresh grow 4 775