【问题标题】:Python Pandas stack by zip code and group by month/yearPython Pandas 按邮政编码堆叠并按月/年分组
【发布时间】:2019-05-04 18:20:12
【问题描述】:

我有一个包含交易数据的大型数据框。我想要做的是使用 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()

非常感谢任何和所有帮助

【问题讨论】:

    标签: python-3.x pandas group-by time-series zipcode


    【解决方案1】:

    如果需要按 zip 和按月分组,我相信您需要将列 ZipCode 添加到 groupby

    per = df.Date.dt.to_period("M")
    df1 = df.groupby(['ZipCode',per])['Transactions'].sum().reset_index() 
    

    【讨论】:

    • 谢谢!像魅力一样工作!
    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多