【问题标题】:Join to dataframes based on index where the second dataframe has repeated indexes related to the first dataframe根据索引加入数据帧,其中第二个数据帧具有与第一个数据帧相关的重复索引
【发布时间】:2022-07-21 00:01:55
【问题描述】:

我有两个数据帧,其中第一个数据帧的索引从零开始。第二个数据帧具有从零开始的重复索引。我想根据它们的索引加入两个数据框。 第一个数据框是这样的

      Start_Year    End_Year
0      1500      1500
1      1500      1501
2      1500      1700
3      1500      1800
4      1500      1800
... ... ...
3409    2018    2018
3410    2018    2018
3411    2019    2019
3412    2019    2022
3413    2020    2020
3414 rows × 2 columns

第二个数据框是

0                       [KingdomofPoland, Georgia]
0                 [GrandDuchyofLithuania, Georgia]
1                   [NorthernYuanDynasty, Georgia]
2                 [SpanishEmpire, ChechenRepublic]
2       [CaptaincyGeneralofChile, ChechenRepublic]
                           ...                    
3411             [SyrianOpposition, SpanishEmpire]
3412                 [UnitedStates, SpanishEmpire]
3412                [UnitedKingdom, SpanishEmpire]
3412                  [SaudiArabia, SpanishEmpire]
3413                              [Turkey, Russia]
Length: 31170, dtype: object

我想根据索引加入这两个数据框,即新的数据框应该看起来像

      Start_Year    End_Year        new_col
0      1500         1500        [KingdomofPoland, Georgia]
0      1500         1500        [GrandDuchyofLithuania, Georgia]
1      1500         1501        [NorthernYuanDynasty, Georgia]
2      1500         1700        [SpanishEmpire, ChechenRepublic]
2      1500         1700        [CaptaincyGeneralofChile, ChechenRepublic]
......
3411    2019        2019        [SyrianOpposition, SpanishEmpire]
3412    2019        2022        [UnitedStates, SpanishEmpire]
3412    2019        2022        [UnitedKingdom, SpanishEmpire]
3412    2019        2022        [SaudiArabia, SpanishEmpire]
.......

这本质上是我需要根据在第二个数据帧中重复相同索引的次数来复制数据帧 1 的行。如我们所见,在第二个数据帧中,零索引出现了两次,因此我们将数据帧 1 的零索引行复制两次,然后加入数据帧,依此类推。最后我们可以重置索引(我知道)。

我附上了两个数据框的链接以供参考。 第一个数据帧的链接https://drive.google.com/file/d/1DqxhnMM8R21Olm9zeRJeDgua_ozoRp8P/view?usp=sharing

第二个数据框的链接https://drive.google.com/file/d/1sX5xcTeovVqXtZgSZ5cTC5JRdUvaw7gd/view?usp=sharing

我不知道如何处理这些任务。请帮帮我。

【问题讨论】:

    标签: python pandas dataframe numpy data-science


    【解决方案1】:

    Pandas 加入会满足您的要求。

    举个例子

    df1 = pd.DataFrame({'a': [0, 1], 'b': [1500, 1501]})
    df2 = pd.DataFrame({'a': [0, 0, 1, 1], 'c': ['a', 'b', 'c', 'd']})
    df1.set_index('a', inplace=True)
    df2.set_index('a', inplace=True)
    

    我们有两个数据框:

       a     b
    0  0  1500
    1  1  1501
    

       a  c
    0  0  a
    1  0  b
    2  1  c
    3  1  d
    

    现在

    df = df2.join(df1)[['b', 'c']]
    

    将是数据框

          b  c
    a         
    0  1500  a
    0  1500  b
    1  1501  c
    1  1501  d
    

    【讨论】:

      猜你喜欢
      • 2020-05-26
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2021-10-27
      • 2020-06-22
      • 2020-03-13
      • 2012-08-13
      相关资源
      最近更新 更多