首页 > 解决方案 > 根据列中的字符串合并 DataFrames 列表,然后将其转换为字典

问题描述

任务描述

我想基于列(国家/地区)中的字符串合并 DataFrame 列表,然后将其转换为字典,并将 Country 列作为键,合并后的 DataFrame 作为值。数据示例:

国名列表

country_names = ['ITA', USA', 'UK', 'ARG']

命名的 DataFrame 列表df_countries

df_countries[0]

  index   Date      A   B   C  Country     
    1   2019-12-31  x   y   z    ITA
    2   2019-12-30  x   y   z    ITA    

df_countries[1]

  index   Date      A   B   C  Country     
    1   2019-12-31  x   y   z    ITA
    2   2019-12-30  x   y   z    ITA    

df_countries[2]

  index   Date      A   B   C  Country     
    1   2019-12-31  x   y   z    USA
    2   2019-12-30  x   y   z    USA    

df_countries[3]

  index   Date      A   B   C  Country     
    1   2019-12-31  x   y   z    ARG
    2   2019-12-30  x   y   z    ARG    

例如,我希望 ITA 在合并后看起来像下面这样,然后以 ITA 作为键等创建一个字典:

  index   Date      A   B   C  Country     
    1   2019-12-31  x   y   z    ITA
    2   2019-12-30  x   y   z    ITA       
    3   2019-12-31  x   y   z    ITA
    4   2019-12-30  x   y   z    ITA  

任何帮助都会很棒!

标签: pythonlistloopsdataframedictionary

解决方案


从我的评论中进行了一些详细说明:您可以首先将所有数据框与 合并pd.concat(),然后选择匹配的行并从中创建新的数据框:

merged_frame = pd.concat(df_countries)
country_dict = {}
for country in country_names:
    country_dict[country] = merged_frame[merged_frame['Country'] == country]

您也可以选择调用country_dict[country].reset_index()来修复新帧的索引。


推荐阅读