【问题标题】:Sum of values with same month同月值的总和
【发布时间】:2016-06-28 15:14:27
【问题描述】:
data = {'dates': ['2010-01-29', '2011-06-14', '2012-01-18'], 'values': [4, 3, 8]}
df = pd.DataFrame(data)
df.set_index('dates')
df.index = df.index.astype('datetime64[ns]')

有一个索引是日期的数据框,我将如何添加一个名为“月份”的新列,它是该月所有值的总和,但不会像说它那样“进入未来”仅在其日期前几天累加。

这就是列的样子。

'Month': [4, 3, 12] 

【问题讨论】:

  • 这些是对应日期的值,4 代表 '2010-01-29',8 代表 '2012-01-18'

标签: python pandas


【解决方案1】:

你可以使用熊猫TimeGrouper

df.groupby(pd.TimeGrouper('M')).sum()

【讨论】:

  • 忘了TimeGrouper,这就是这样做的方法。
  • pd.TimeGrouper() 在 pandas v0.21.0 中被正式弃用,取而代之的是 pd.Grouper()。见here
【解决方案2】:

apply是你的朋友

def sum_from_months_prior(row, df):
    '''returns sum of values in row month, 
    from all dates in df prior to row date'''

    month = pd.to_datetime(row).month

    all_dates_prior = df[df.index <= row]
    same_month = all_dates_prior[all_dates_prior.index.month == month]

    return same_month["values"].sum()

data = {'dates': ['2010-01-29', '2011-06-14', '2012-01-18'], 'values': [4, 3, 8]}
df = pd.DataFrame(data)
df.set_index('dates', inplace = True)
df.index = pd.to_datetime(df.index)
df["dates"] = df.index
df.sort_index(inplace = True)

df["Month"] = df["dates"].apply(lambda row: sum_from_months_prior (row, df))
df.drop("dates", axis = 1, inplace = True)

所需的 df:

            values  Month
dates
2010-01-29       4      4
2011-06-14       3      3
2012-01-18       8     12

【讨论】:

    【解决方案3】:

    有几种方法可以做到这一点。第一种是使用df.resample(...).sum() 重新采样到每月。

    您还可以使用 df['month'] = df.index.month 从索引中创建月份列,然后执行 groupby 操作 df.groupby('month').sum() - 哪种方法最好取决于您要对数据执行的操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 2017-08-20
      • 2015-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多