合并不同的值

2024-09-27 04:23:45 发布

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

我需要在Bidfloor列中插入一个特定的值,但我的问题是当我运行df_g['Bidfloor'] = df_g[['Sitio', 'Country']].merge(df_seg, how='left').Precio时,Bidfloor列将值作为NaN而不是floorprice的值,并且我对df_g['Bidfloor'] = df_g[['Sitio', 'Espacio', 'Country']].merge(df_seg, how='left').Precio也有同样的问题

floorprice = 0.17
df_g = pd.read_csv('este_mes.csv')
df_g = df_g[df_g.Subastas > 1000]
df_g.to_csv('aaaa.csv')
df_seg = pd.read_csv('output.csv', names=['Espacio', 'Country', 'Precio', 'Sitio'])
df_g['Bidfloor'] = floorprice
df_g['Bidfloor'] = df_g[['Sitio', 'Country']].merge(df_seg, how='left').Precio
df_g['Bidfloor'] = df_g[['Sitio', 'Espacio', 'Country']].merge(df_seg, how='left').Precio
df_g.to_csv('Analizador_{}.csv'.format(auth), index=False)

输出:

Sitio,Espacio,Tamano,Country,Impresiones_exchange,Importe_a_cobrar,eCPM,Subastas,Fill_rate,Bidfloor
A,3619717 - www.A.com.ar - Seccion - Seccion300x250B,300x250,DE - Germany,846,0.21,0.25,1312,64.48,0.1
B,3619717 - www.A.com.ar - Seccion - Seccion300x250B,300x250,AR - Argentina,846,0.21,0.25,1312,64.48,NaN

我需要的输出:

Sitio,Espacio,Tamano,Country,Impresiones_exchange,Importe_a_cobrar,eCPM,Subastas,Fill_rate,Bidfloor
A,3619717 - www.A.com.ar - Seccion - Seccion300x250B,300x250,DE - Germany,846,0.21,0.25,1312,64.48,0.1
B,3619717 - www.A.com.ar - Seccion - Seccion300x250B,300x250,AR - Argentina,846,0.21,0.25,1312,64.48,0.2

数据框g:

Sitio,Espacio,Tamano,Country,Impresiones_exchange,Importe_a_cobrar,eCPM,Subastas,Fill_rate
A,3619717 - www.A.com.ar - Seccion - Seccion300x250B,300x250,DE - Germany,846,0.21,0.25,1312,64.48
B,3619717 - www.A.com.ar - Seccion - Seccion300x250B,300x250,AR - Argentina,846,0.21,0.25,1312,64.48

数据框分段:

Espacio,Country,Precio,Sitio
3619717 - www.A.com.ar - Seccion - Seccion300x250B,DE - Germany,0.1,A
*,AR - Argentina,0.2,A

Tags: csvcomdfwwwmergecountryhowar
1条回答
网友
1楼 · 发布于 2024-09-27 04:23:45

我认为你的潜在问题是你的merge语句不够具体。作为Pandas merge documentation says,如果不为on参数设置任何值,并且保留left_indexright_index参数false,那么pandas默认情况下会在列的交集上合并。这意味着它仅在每个公共列的值相同时才连接行

在您的示例中,由于Sitio列的原因,合并不会为第二行返回任何内容。在df_g中,此列的第二行的值为'B',而在df_seg中,第二行的值为'a':

Initial DataFrame Values

当以这种方式运行合并时,只返回第一行: Simple Merge

在合并之前,您需要从数据帧中删除Sitio列: Simple Merge 2

显式指定要合并的列: Explicit List of Columns

或基于某些共享索引进行合并: Index Merge

Here是一个链接,指向我用于此的废弃代码(如果它看起来有点奇怪,对不起,Gists似乎不能很好地处理Jupyter笔记本)

相关问题 更多 >

    热门问题