【问题标题】:How can a list of pandas DataFrames be merged while keeping duplicate indices?如何在保留重复索引的同时合并 pandas DataFrames 列表?
【发布时间】:2018-11-11 23:09:26
【问题描述】:

我有许多 DataFrame 的列表。每个 DataFrame 是一组与时间戳相对应的各种测量值。由于许多测量可以对应于同一时刻,因此 DataFrame 的时间索引中有许多重复的索引条目。

我想合并这个 DataFrame 列表,显然是为了保留重复的索引。如何才能做到这一点?我已经检查了this question,但这些解决方案适用于仅合并两个 DataFrame 的情况,而不是许多 DataFrame 的列表。 concat 功能显然是 cannot handle 重复索引。

【问题讨论】:

标签: pandas dataframe merge concatenation


【解决方案1】:

见@HarvIpan 评论:这是正确的。您可以将列表连接到熊猫数据框:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3],'b':['a','b','c']})
df.set_index('a', inplace=True)

df2 = pd.DataFrame({'a':[1,2,3],'b':['d','e','f']})
df2.set_index('a', inplace=True)

df3 = pd.DataFrame({'a':[1,2,3],'c':['g','e','h']})
df3.set_index('a', inplace=True)

list_of_dfs = [df,df2,df3]

pd.concat(list_of_dfs, sort=False)

    b   c
a       
1   a   NaN
2   b   NaN
3   c   NaN
1   d   NaN
2   e   NaN
3   f   NaN
1   NaN g
2   NaN e
3   NaN h

【讨论】:

    猜你喜欢
    • 2018-01-29
    • 2012-11-14
    • 2012-08-12
    • 1970-01-01
    • 2020-09-04
    • 2022-01-22
    • 2013-09-08
    • 2018-10-19
    • 2017-05-10
    相关资源
    最近更新 更多