熊猫按月分组与转置

数据挖掘 Python 熊猫
2021-09-28 00:35:16

基于以下数据框,我正在尝试按月份、类型和文本创建分组,我认为我接近我想要的,但是我无法按我想要的方式按月分组,所以我必须使用该列翻译。但是,当我转置这个时,我失去了订单

df = pd.DataFrame({'date':['6/2/2017','5/23/2017','5/20/2017','6/22/2017','4/21/2017','7/2/2017','5/23/2017','5/20/2017','8/22/2017','2/21/2017'],'rev':[100,200,300,400,500,-70,-250,-200,400,500],'text':['Car','House','Car','Truck','House','Car','House','Car','Truck','House']})
df['date'] = pd.to_datetime(df['date'])
df = df.sort_values('date')
#New Column
df['transdate'] = pd.to_datetime(df['date'])
df['transdate'] = df['transdate'].dt.strftime('%B - %Y')
#second new column
df['type'] = np.where(df['rev']>0, 'positive', 'negative')

这给了我这个:

在此处输入图像描述

然后,我创建一个要转置的数据透视表

df_pivot = df.pivot_table(index='transdate',columns=['type','text'],aggfunc=sum, fill_value=0).T
df_pivot

在此处输入图像描述

我想知道如何对第一行进行排序,从 2017 年 2 月开始,然后是 2017 年 4 月,依此类推?或者,从 2017 年 8 月开始,然后从 2017 年 7 月开始……但保持月份顺序?

或者,最好用索引日期做数据透视表,然后进行分组?如果是这种情况,我该如何进行分组?

2个回答
# make a month column to preserve the order
df['month'] = pd.to_datetime(df['date']).dt.strftime('%m')

# create the pivot table with this numeric month column
df_pivot = df.pivot_table(index='month',columns=['type','text'],aggfunc=sum, fill_value=0).T

# create a mapping between numeric months and the English version
mapping = pd.Series(df.transdate.tolist(),index=df.month.values).drop_duplicates()

# replace the columns according to the mapping
df_pivot.columns = [i for i in map(mapping.get, df_pivot.columns)]

它正在排序,但它不知道它是日期类型,因此它是按字母顺序排序的。我鼓励您将其更改为 ofdatetime并再次执行相同操作。

否则小技巧,用整数替换月份的名称,并使其类似于 201701 for January, 201704 for April,但这不受欢迎。但可能对你有用。