【问题标题】:Merging/Concat non unique multi index with Date使用日期合并/连接非唯一多索引
【发布时间】:2020-03-05 23:33:48
【问题描述】:

我有 2 个数据框如下:

df1 =

City       Date           Data1
LA         2020-01-01     20
LA         2020-01-02     30
NY         2020-01-01     50

df2 = 

City       Date           Data2
LA         2020-01-01     2.5
LA         2020-01-02     1
LA         2020-01-03     7
NY         2020-01-01     6.5

我想根据“城市”和“日期”合并或连接它们,这样结果将是:

City       Date           Data1    Data2
LA         2020-01-01     20       2.5
LA         2020-01-02     30       1
NY         2020-01-01     50       6.5

我尝试了什么:

pd.concat([df1.set_index(['Country','Date'],[df1.set_index(['Country','Date'])], axis = 1)

我得到错误: ValueError: 无法处理非唯一的多索引!

我也不能合并,因为我有日期作为索引。

【问题讨论】:

    标签: pandas concat


    【解决方案1】:

    想法是由GroupBy.cumcount 创建的新列对重复数据删除:

    print (df2)
      City        Date  Data2
    0   LA  2020-01-01    2.5
    1   LA  2020-01-02    1.0 <- duplicates
    2   LA  2020-01-02    7.0 <- duplicates
    3   NY  2020-01-01    6.5
    
    df1 = (df1.assign(g = df1.groupby(['City','Date']).cumcount())
              .set_index(['City','Date','g']))
    df2 = (df2.assign(g = df2.groupby(['City','Date']).cumcount())
              .set_index(['City','Date','g']))
    
    df = pd.concat([df1, df2], axis = 1)
    print (df)
                       Data1  Data2
    City Date       g              
    LA   2020-01-01 0   20.0    2.5
         2020-01-02 0   30.0    1.0
                    1    NaN    7.0
    NY   2020-01-01 0   50.0    6.5
    

    如果需要删除助手级别g

    df = pd.concat([df1, df2], axis = 1).reset_index(level=2, drop=True)
    print (df)
                     Data1  Data2
    City Date                    
    LA   2020-01-01   20.0    2.5
         2020-01-02   30.0    1.0
         2020-01-02    NaN    7.0
    NY   2020-01-01   50.0    6.5
    

    编辑:我认为这里有必要将两列都转换为 DataFrame,然后使用 DataFrame.merge 的内连接:

    df1['Date'] = pd.to_datetime(df1['Date'])
    df2['Date'] = pd.to_datetime(df2['Date'])
    
    df = df1.merge(df2, on=['City','Date'])
    print (df)
      City       Date  Data1  Data2
    0   LA 2020-01-01     20    2.5
    1   LA 2020-01-02     30    1.0
    2   NY 2020-01-01     50    6.5
    

    【讨论】:

    • 你好 jezrael,我认为这里有一点误解。如您所见,df2 中没有重复项。 df2 比 df1 拥有更多的数据(行),我只想合并/合并那些具有相同索引的数据。谢谢。
    • @tetehMay - 所以你需要df = df1.merge(df2, on=['City','Date']) ?
    • 是的,我试过了,但是python说我必须使用pd.concat来合并日期。
    • ValueError: 您正在尝试合并 datetime64[ns] 和对象列。如果你想继续,你应该使用 pd.concat
    猜你喜欢
    • 1970-01-01
    • 2020-10-21
    • 2023-03-08
    • 1970-01-01
    • 2015-06-21
    • 2016-05-01
    • 2019-01-21
    • 2021-12-08
    相关资源
    最近更新 更多