【问题标题】:combining dataframes and adding values on common date index合并数据框并在通用日期索引上添加值
【发布时间】:2021-11-28 02:19:13
【问题描述】:

我有许多数据框,其中有一列(所有名称相同),其索引是日期范围 - 我想将这些数据框合并/合并为一个,将任何日期常见的值相加。下面是一个简化的例子

range1 = pd.date_range('2021-10-01','2021-11-01')
range2 = pd.date_range('2021-11-01','2021-12-01')

df1 = pd.DataFrame(np.random.rand(len(range1),1), columns=['value'], index=range1)
df2 = pd.DataFrame(np.random.rand(len(range2),1), columns=['value'], index=range2)

这里 '2021-11-01' 出现在 df1 和 df2 中,具有不同的值

我想获得一个包含 62 行 (32+31-1) 的数据框,其中 2021-11-01 日期包含其在 df1 和 df2 中的值的总和

【问题讨论】:

  • 您可以使用df = pd.concat([df1,df2..], axis=0) 连接数据帧,然后使用df.groupby,例如df.groupby('date)['value'].sum()`

标签: python pandas dataframe


【解决方案1】:

我们可以在两个数据帧上使用pd.concate(),然后df.reset_index()得到一个新的正则整数索引,重命名日期列,然后使用df.groupby().sum()

df = pd.concat([df1,df2]) # this gives 63 rows by 1 column, where the column is the values and the dates are the index
df = df.reset_index() # moves the dates to a column, now called 'index', and makes a new integer index
df = df.rename(columns={'index':'Date'}) #renames the column
df.groupby('Date').sum()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2018-06-10
    • 1970-01-01
    相关资源
    最近更新 更多