我的pandas数据框由一个分类列JOB_TITLE,一个数字列BASE_SALARY和一个日期时间索引JOIN_DATE组成.我想对分类和下采样日期时间组进行聚合,如下所示:
# Resampled at frequency of start data of every 5 years
mean_agg = (df
.groupby('JOB_TITLE')
.resample('5AS')['BASE_SALARY']
.mean())
不幸的是,由于groupby操作在重采样之前发生,因此对每个JOB_TITLE组独立地执行重采样操作.这导致以下系列:
| JOB_TITLE | JOIN_DATE | |
|-------------------|------------|-------|
| Data Scientist | 2004-01-01 | 60000 |
| | 2009-01-01 | 75000 |
| | 2014-01-01 | 90000 |
| | | |
| Software Engineer | 2001-01-01 | 70000 |
| | 2006-01-01 | 85000 |
| | 2011-01-01 | 90000 |
| | 2016-01-01 | 85000 |
正如您所看到的,Data Scientist组和软件工程师在JOIN_DATE级别的索引未对齐.当您为级别JOB_TITLE应用unstack时,这会产生一个问题,如下所示:
mean_agg.unstack('JOB_TITLE')
这导致以下数据帧:
| JOB_TITLE | Data Scientist | Software Engineer |
|------------|----------------|-------------------|
| JOIN_DATE | | |
| 2001-01-01 | NaN | 70000 |
| 2004-01-01 | 60000 | NaN |
| 2006-01-01 | NaN | 85000 |
| 2009-01-01 | 75000 | NaN |
| 2011-01-01 | NaN | 70000 |
| 2014-01-01 | 90000 | NaN |
| 2016-01-01 | NaN | 85000 |
如何避免groupby和resample的顺序操作,而是执行同步操作?谢谢!
最佳答案
更新Pandas 0.21回答:pd.TimeGrouper is getting deprecated,改用pd.Grouper.
mean_agg = (df.groupby(['JOB_TITLE',pd.Grouper(freq='5AS')])['BASE_SALARY']
.mean())
mean_agg.unstack('JOB_TITLE')
我们尝试使用pd.TimeGrouper,而不是使用resample
mean_agg = (df
.groupby(['JOB_TITLE',pd.TimeGrouper(freq='5AS')])['BASE_SALARY']
.mean())
mean_agg.unstack('JOB_TITLE')
TimeGrouper对齐分组时间范围的区间.