Python 按日期重新组织数据帧
我有一个数据透视表,它按月显示客户呼叫。看起来像这样Python 按日期重新组织数据帧,python,pandas,dataframe,pivot-table,Python,Pandas,Dataframe,Pivot Table,我有一个数据透视表,它按月显示客户呼叫。看起来像这样 CompanyName 1 2 3 4 5 6 7 8 9 10 11 12 Customer 1 17 30 29 39 15 27 15 10 36 21 18 15 Customer 2 4 11 13 22 34 27 32 17 29 31 17 14 Customer 3 10 7 23 21 7 15 25 0 21
CompanyName 1 2 3 4 5 6 7 8 9 10 11 12
Customer 1 17 30 29 39 15 27 15 10 36 21 18 15
Customer 2 4 11 13 22 34 27 32 17 29 31 17 14
Customer 3 10 7 23 21 7 15 25 0 21 9 12 17
Customer 4 6 10 11 8 3 4 3 8 11 11 18 14
Customer 5 13 7 6 12 6 8 2 10 11 7 10 11
我制作了一个日期列表,以便在图表上很好地显示它们
date_list[::-1]
Out[63]:
['Jul 2015',
'Jun 2015',
'May 2015',
'Apr 2015',
'Mar 2015',
'Feb 2015',
'Jan 2015',
'Dec 2014',
'Nov 2014',
'Oct 2014',
'Sep 2014',
'Aug 2014']
我想对数据透视表重新排序,使其与日期列表匹配,如下所示:
CompanyName 7 8 9 10 11 12 1 2 3 4 5 6
Customer 1 15 10 36 21 18 15 17 30 29 39 15 27
Customer 2 32 17 29 31 17 14 4 11 13 22 34 27
Customer 3 25 0 21 9 12 17 10 7 23 21 7 15
Customer 4 3 8 11 11 18 14 6 10 11 8 3 4
Customer 5 2 10 11 7 10 11 13 7 6 12 6 8
我正在研究如何重新排序列,但由于它将按月动态变化,我有点困惑 假设
df
是您的数据透视表
df
1 2 3 4 5 ... 8 9 10 11 12
CompanyName ...
Customer1 17 30 29 39 15 ... 10 36 21 18 15
Customer2 4 11 13 22 34 ... 17 29 31 17 14
Customer3 10 7 23 21 7 ... 0 21 9 12 17
Customer4 6 10 11 8 3 ... 8 11 11 18 14
Customer5 13 7 6 12 6 ... 10 11 7 10 11
您可以使用pd.concat来实现这一技巧
pd.concat([df.iloc[:,6:], df.iloc[:,:6]], axis=1)
7 8 9 10 11 ... 2 3 4 5 6
CompanyName ...
Customer1 15 10 36 21 18 ... 30 29 39 15 27
Customer2 32 17 29 31 17 ... 11 13 22 34 27
Customer3 25 0 21 9 12 ... 7 23 21 7 15
Customer4 3 8 11 11 18 ... 10 11 8 3 4
Customer5 2 10 11 7 10 ... 7 6 12 6 8
[5 rows x 12 columns]
假设您的数据透视表名为
pt
# Months are off by one because of Python's zero based indexing.
months = {'Jan': 0,
'Feb': 1,
'Mar': 2,
'Apr': 3,
'May': 4,
'Jun': 5,
'Jul': 6,
'Aug': 7,
'Sep': 8,
'Oct': 9,
'Nov': 10,
'Dec': 11}
# Get the index value of the first month from your list.
month = months[date_list[0][:3]]
# Now concatenate the results and create you column names.
pt_new = pd.concat([pt.iloc[:, month:], pt.iloc[:, :month]], axis=1)
pt_new.columns = date_list
>>> pt_new
Aug 2014 Sep 2014 Oct 2014 Nov 2014 Dec 2014 Jan 2015
Customer 1 10 36 21 18 15 17
Customer 2 17 29 31 17 14 4
Customer 3 0 21 9 12 17 10
Customer 4 8 11 11 18 14 6
Customer 5 10 11 7 10 11 13
Feb 2015 Mar 2015 Apr 2015 May 2015 Jun 2015 Jul 2015
Customer 1 30 29 39 15 27 15
Customer 2 11 13 22 34 27 32
Customer 3 7 23 21 7 15 25
Customer 4 10 11 8 3 4 3
Customer 5 7 6 12 6 8 2
我喜欢这个,因为它是一个单行程序,但一旦我们进入8月份它就不会更新,那么它必须是pd.concat([df.iloc[:,7:],df.iloc[:,:7]],axis=1)这个答案也有同样的问题,一旦你使用month=months[date_list[0][:3]]得到月份,它就停滞不前了。我希望它每月根据月份进行更改。行
month=months[date\u list[0][:3]]
使用字典获取日期列表中第一个月的索引值。如果列表更改,索引值将更改,因此表列将移动。啊,我现在看到了。非常感谢。