【发布时间】:2017-10-18 21:03:46
【问题描述】:
我的时间序列数据有一列可以取值 A、B 或 C。
我的数据示例如下所示:
date,category
2017-01-01,A
2017-01-15,B
2017-01-20,A
2017-02-02,C
2017-02-03,A
2017-02-05,C
2017-02-08,C
我想按月对我的数据进行分组,并将 A 的计数和 B 的计数的总和存储在 a_or_b_count 列中,并将 C 的计数存储在 c_count 中。
我已经尝试了几件事,但我能做的最接近的是使用以下函数预处理数据:
def preprocess(df):
# Remove everything more granular than day by splitting the stringified version of the date.
df['date'] = pd.to_datetime(df['date'].apply(lambda t: t.replace('\ufeff', '')), format="%Y-%m-%d")
# Set the time column as the index and drop redundant time column now that time is indexed. Do this op in-place.
df = df.set_index(df.date)
df.drop('date', inplace=True, axis=1)
# Group all events by (year, month) and count category by values.
counted_events = df.groupby([(df.index.year), (df.index.month)], as_index=True).category.value_counts()
counted_events.index.names = ["year", "month", "category"]
return counted_events
这给了我以下信息:
year month category
2017 1 A 2
B 1
2 C 3
A 1
总结所有 A 和 B 的过程将是相当手动的,因为在这种情况下类别成为索引的一部分。
我是一个绝对的熊猫威胁,所以我可能会比实际更难。任何人都可以提供有关如何在 pandas 中实现此分组的提示吗?
【问题讨论】:
标签: python-3.x pandas group-by time-series