【问题标题】:How can I concatenate data frames stored as dictionary keys into a single data frame? [duplicate]如何将存储为字典键的数据帧连接到单个数据帧中? [复制]
【发布时间】:2018-11-07 01:35:17
【问题描述】:

我有一个包含 120 个键的字典,每个键都包含一个数据框。我如何以编程方式(使用pd.concat)将它们连接成一个大数据框?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用pd.concat(d.values()) 简单地连接字典的值:

    >>> d = {1:pd.DataFrame(np.random.random((5,5))),2:pd.DataFrame(np.random.random((5,5)))}
    >>> d
    {1:           0         1         2         3         4
    0  0.319556  0.540776  0.988554  0.775070  0.535067
    1  0.383192  0.379474  0.204998  0.948605  0.785190
    2  0.006732  0.362755  0.537260  0.854110  0.409386
    3  0.795973  0.073652  0.796565  0.168206  0.814202
    4  0.531702  0.524501  0.002366  0.631852  0.024509, 
    
    2:           0         1         2         3         4
    0  0.369098  0.125491  0.832362  0.183199  0.729110
    1  0.069843  0.337424  0.476837  0.078589  0.489447
    2  0.504904  0.456996  0.239802  0.025953  0.609697
    3  0.262001  0.646389  0.992928  0.124552  0.878561
    4  0.707881  0.520429  0.609257  0.018488  0.167053}
    
    >>> new_df = pd.concat(d.values())
    >>> new_df
              0         1         2         3         4
    0  0.319556  0.540776  0.988554  0.775070  0.535067
    1  0.383192  0.379474  0.204998  0.948605  0.785190
    2  0.006732  0.362755  0.537260  0.854110  0.409386
    3  0.795973  0.073652  0.796565  0.168206  0.814202
    4  0.531702  0.524501  0.002366  0.631852  0.024509
    0  0.369098  0.125491  0.832362  0.183199  0.729110
    1  0.069843  0.337424  0.476837  0.078589  0.489447
    2  0.504904  0.456996  0.239802  0.025953  0.609697
    3  0.262001  0.646389  0.992928  0.124552  0.878561
    4  0.707881  0.520429  0.609257  0.018488  0.167053
    

    【讨论】:

    • 上述答案与将我的 dict 中的每个 dfs 添加到列表然后连接它们之间有什么区别吗? list_of_dfs= [] for key in dict_of_dfs.keys(): list_of_dfs.append(dict_of_dfs[key]) df_overall = pd.concat(list_of_dfs)
    • 我认为唯一的区别是您正在添加一个列表的创建,它使用内存和时间,这两者都可以通过 not 创建这些列表来保存
    猜你喜欢
    • 2018-02-27
    • 2018-10-11
    • 1970-01-01
    • 2020-08-10
    • 2022-10-12
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多