使用数据帧合并(连接)4个具有不同ID和多个值的不同CSV文件

2024-05-13 07:08:40 发布

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

我有4个不同的CSV文件,我想合并(加入)。 主文件包含所有列,并包含其他文件之一的标识符(联接列)

例如,主文件包含:

Name           | Address             | ID_1  | ID_2        | ID_3
Ruth D. Batie  | 4962 Hill Street    | 1_001 | NaN         | 3_004
Kelley C. Rice | 1074 Tipple Road    | NaN   | 2_002       | NaN
Gary P. Kirby  | 1520 Robinson Court | 1_004 | 2_002;2_004 | 3_004

文件查找1包含:

ID_1  | Monthly_MB
1_001 | 1557
1_002 | 1024
1_003 | 500
1_004 | 24

文件查找2包含:

ID_2  | platform
2_001 | ios
2_002 | android
2_003 | ios
2_004 | ios

文件查找3包含:

ID_3  | Device
3_001 | T31
3_002 | IN265
3_003 | AG_Flair
3_004 | BOOST2

最后我想说:

Name           | Address             | ID_1  | ID_2        | ID_3
Ruth D. Batie  | 4962 Hill Street    | 1557  | NaN         | BOOST2
Kelley C. Rice | 1074 Tipple Road    | NaN   | android     | NaN
Gary P. Kirby  | 1520 Robinson Court | 24    | android;ios | BOOST2 

我的一些代码:

result = pd.merge(df_main,
                 df_1[['ID_1', 'Monthly_MB']],
                 df_2[['ID_2', 'platform']],
                 df_3[['ID_3', 'Device']],
                 on=' ??')
result.head()

然后我对内部连接部分(on='')感到迷茫,因为有不同的列要连接,一列包含两个值(甚至可以超过2个值),用分号分隔

Gary P. Kirby  | 1520 Robinson Court | 1_004 | 2_002;2_004 | 3_004

我对熊猫还很陌生,所以非常感谢你的帮助


Tags: 文件nameiddfaddressnanandroidios
2条回答

您可以使用下面的代码来匹配/替换这些值。 添加用于检测具有多个值的单元格的if语句,并用分号拆分这些值:

for i in df_main['ID_1']:
    df_main.loc[df_main['ID_1']==i , 'ID_1'] = df_1.loc[df_1['ID_1']==i , 'Monthly_MB']

我建议首先使用^{}^{}创建包含所有查找文件的字典:

d = {'ID_1' : df2.set_index('ID_1')['Monthly_MB'].to_dict(),
     'ID_2' : df3.set_index('ID_2')['platform'].to_dict(),
     'ID_3' : df4.set_index('ID_3')['Device'].to_dict()}

然后按字典的所有键循环并使用列表理解-首先按;拆分值如果是字符串,则按字典映射,然后按join返回;

for c in d.keys():
    f = lambda x: ';'.join(str(d[c].get(y, '')) for y in x.split(';')) 
                                                if isinstance(x, str) 
                                                else x
    df1[c] = df1[c].apply(f)

print (df1)
             Name              Address  ID_1         ID_2    ID_3
0  Ruth D. Batie   4962 Hill Street     1557  NaN          BOOST2
1  Kelley C. Rice  1074 Tipple Road     NaN   android      NaN   
2  Gary P. Kirby   1520 Robinson Court  24    android;ios  BOOST2

相关问题 更多 >