TypeError:merge()至少接受2个参数(给定4个)

import pandas as pd
import numpy as np

'''This is first dataframe'''

df1=pd.DataFrame({'fruit': ['apple', 'banana', 'orange']*3,'weight':['high','medium','low']*3 
                  ,'price': np.random.randint(0, 15, 9)})

'''This is first dataframe'''

df2=pd.DataFrame({'product': ['apple', 'orange', 'pine'] * 2,
                    'kilo': ['high', 'low'] * 3,
                    'price': np.random.randint(0, 15, 6)})

'''我要在两个数据帧上执行合并操作'''

merged=pd.merge(left_on=['fruit','weight'],right_on=['product','kilo'],how='inner',suffixes= 
                ['_left','_right'])

'''它给出了一个我不明白为什么的类型错误'''

评论
苍老师
苍老师

您还需要提供要合并的数据框。尝试这个:

merged=df1.merge(df2, left_on=['fruit','weight'],right_on=['product','kilo'],how='inner',suffixes= 
                ['_left','_right'])

输出:

    fruit weight  price_left product  kilo  price_right
0   apple   high           6   apple  high            5
1   apple   high           9   apple  high            5
2   apple   high           2   apple  high            5
3  orange    low           5  orange   low            2
4  orange    low           5  orange   low            2
5  orange    low          11  orange   low            2
点赞
评论
lquia
lquia

您必须声明要合并的左右数据框:

merged=pd.merge(left=df1, right=df2,left_on=['fruit','weight'],right_on=['product','kilo'],how='inner',suffixes= 
                ['_left','_right'])

输出:

    fruit   weight  price_left  product   kilo  price_right
0   apple   high    4            apple    high  5
1   apple   high    11           apple    high  5
2   apple   high    8            apple    high  5
3   orange  low     7            orange   low   7
4   orange  low     1            orange   low   7
5   orange  low     9            orange   low   7
点赞
评论