我有一个包含交易数据的大数据框。我想做的是使用python汇总从邮政编码开始的数据,然后是年份和月份,最后是该月的交易总数。
我的Df:
Date VAR1 VAR2 ZipCode Transactions
YYYY-MM-DD. X. Y. 12345. 1.
所以我要做的第一件事就是将日期时间转换为日期时间
df['Date'] = pd.to_datetime(df['Date'])
df.info()
# Date datetime64[ns]
然后,我将数据分为年月和交易数:
# grouping the data by year and month
per = df.Date.dt.to_period("M")
g = df.groupby(per)
g.sum() # so now that this works, we need to break it up into zip codes
输出为:
Date. Transactions
YYYY-MM. X
YYYY-MM. Y
我的问题是,我缺少什么才能获得邮政编码:
ZipCode. Date. Transactions
123345. YYYY-MM. sum()
非常感谢所有帮助
我认为如果需要按邮政编码和每月分组ZipCode
,groupby
则需要添加列:
per = df.Date.dt.to_period("M")
df1 = df.groupby(['ZipCode',per])['Transactions'].sum().reset_index()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句