Pandas合并数据帧不同的行数重复数据

2024-06-17 19:18:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个要合并的数据帧(df1df2)。我想为df1中的每一行提供price和代码。我如何合并它们,使价格和代码重复,并根据水果排列?我相信我需要把水果作为索引来做这件事

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

多谢各位


Tags: 代码applepricecherrydf1df2melonfruit
1条回答
网友
1楼 · 发布于 2024-06-17 19:18:22

您只需要使用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

相关问题 更多 >