【问题标题】:Merge DataFrames in Python在 Python 中合并数据帧
【发布时间】:2021-11-23 10:59:29
【问题描述】:

我正在尝试将 2 个数据帧与一些重复的索引合并,我想将其替换。

这就是我想用一个简单的例子来做的。我有这个数据框:

df1 = pd.DataFrame({'values': [1, 2, 3]}, index=['a', 'b', 'c'])
df2 = pd.DataFrame({'values': [4, 5, 6]}, index=['c', 'd', 'e'])

我想以某种方式合并它们,结果是一个 DataFrame,索引 = ['a', 'b', 'c', 'd', 'e'] 和值 = [1, 2, 4 , 5, 6]。由于索引“c”在两个 DataFrame 中,我想用新的值替换该值,并且在没有匹配索引的情况下,索引 + 值将作为新行添加。

我该怎么做?

【问题讨论】:

    标签: python dataframe


    【解决方案1】:
    import pandas as pd
    from pandas import Series, DataFrame
    
    df1 = pd.DataFrame({'values': [1, 2, 3]}, index=['a', 'b', 'c'])
    df2 = pd.DataFrame({'values': [4, 5, 6]}, index=['c', 'd', 'e'])
    
    df_new = pd.concat([df1, df2], axis=0)
    print(df_new)
    
    df_new1 = df_new.groupby(df_new.index).first()
    print(df_new1)
    
    df_new2 = df_new.groupby(df_new.index).last()
    print(df_new2)
    
       values
    a       1
    b       2
    c       3
    c       4
    d       5
    e       6
       values
    a       1
    b       2
    c       3
    d       5
    e       6
       values
    a       1
    b       2
    c       4
    d       5
    e       6
    

    【讨论】:

      猜你喜欢
      • 2016-10-17
      • 2022-11-29
      • 2020-03-03
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2018-06-20
      相关资源
      最近更新 更多