【问题标题】:Pandas: concat dataframes熊猫:连接数据框
【发布时间】:2019-09-23 11:36:52
【问题描述】:

我需要合并一组数据框:

df1 = pd.DataFrame({'Lic1': [0,5,7]}, index=['07:00', '08:00', '09:00'])
df2 = pd.DataFrame({'Lic1': [4,2,1]}, index=['10:00', '11:00', '12:00'])
df3 = pd.DataFrame({'Lic2': [1,1,4]}, index=['07:00', '08:00', '10:00'])

得到以下结果:

        Lic1    Lic2
07:00   0.0     1.0
08:00   5.0     1.0
09:00   7.0     NaN
10:00   4.0     4.0
11:00   2.0     NaN
12:00   1.0     NaN

当我使用 concat 时,我得到了正确的列,但索引重复(07:00、08:00 和 10:00,由于新的列名):

df = pd.concat([df1, df2, df3], sort=True, axis=0)
Output:
        Lic1    Lic2
07:00   0.0     NaN
08:00   5.0     NaN
09:00   7.0     NaN
10:00   4.0     NaN
11:00   2.0     NaN
12:00   1.0     NaN
07:00   NaN     1.0
08:00   NaN     1.0
10:00   NaN     4.0

然后我必须合并重复索引以存储最大值并删除重复行,如下所示:

for index in df.index:
    for column in df.columns:
        df.loc[index,column] = df.loc[index, column].max()
df.drop_duplicates(inplace=True)

这给了我请求的输出。

有没有更简单(==更多pandastic)的方式如何一步完成?我尝试使用 concatmergejoin 一步完成,但可能错过了一些东西。我总是在索引中得到重复(如上)或重复列(如带有 concat 的双 Lic1 或带有 merge 的 Lic1_x 和 Lic1_y)。

【问题讨论】:

    标签: pandas concatenation


    【解决方案1】:

    每个索引使用max,与.groupby(level=0).max() 相同:

    df = pd.concat([df1, df2, df3], sort=True, axis=0).max(level=0)
    print (df)
           Lic1  Lic2
    07:00   0.0   1.0
    08:00   5.0   1.0
    09:00   7.0   NaN
    10:00   4.0   4.0
    11:00   2.0   NaN
    12:00   1.0   NaN
    

    【讨论】:

      猜你喜欢
      • 2021-07-12
      • 2020-10-13
      • 2016-03-09
      • 2016-07-21
      • 2023-02-10
      • 2018-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多