在python中合并2列

2024-09-27 07:28:06 发布

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

我需要做与我的函数相同的事情:df_g['Bidfloor'] = df_g[['Sitio', 'Country']].merge(df_seg, how='left').Precio但是在Country上,而不是完全相同的行上,只有前2个键,因为我不能更改数据的语言。所以我只想读取Country列的前两个键,而不是Country列的所有键

数据框g:

Sitio,Country
Los Andes Online,HN - Honduras
Guarda14,US - Estados Unidos
Guarda14,PE - Peru

数据框分段:

Sitio,Country,Precio
Los Andes Online,HN - Honduras,0.5
Guarda14,US - United States,2.1

我需要的是:

Sitio,Country,Bidfloor
Los Andes Online,HN - Honduras,0.5
Guarda14,US - United States,2.1
Guarda14,PE - Peru,NULL

Tags: 数据dfcountryonlineuspehnperu
2条回答

您需要额外的键来帮助合并,我使用cumcount来区分重复值

df1.assign(key=df1.groupby('Sitio').cumcount()).\
  merge(df2.assign(key=df2.groupby('Sitio').cumcount()).
   drop('Country',1),
    how='left',
     on=['Sitio','key'])
Out[1491]: 
              Sitio              Country  key  Precio
0  Los Andes Online        HN - Honduras    0     0.5
1          Guarda14  US - Estados Unidos    0     2.1
2          Guarda14            PE - Peru    1     NaN

只需添加和删除合并列,即可完成:

df_seg['merge_col'] = df_seg.Country.apply(lambda x: x.split('-')[0])

df_g['merge_col'] = df_g.Country.apply(lambda x: x.split('-')[0])

然后做:

df = pd.merge(df_g, df_seg[['merge_col', 'Precio']], on='merge_col', how='left').drop('merge_col', 1)

退货

Sitio   Country Precio
0   Los Andes Online    HN - Honduras   0.5
1   Guarda14    US - Estados Unidos 2.1
2   Guarda14    PE - Peru   NaN

相关问题 更多 >

    热门问题