gpt4 book ai didi

python - 在Python中转置/ reshape 数据

转载 作者:行者123 更新时间:2023-11-28 21:32:36 25 4
gpt4 key购买 nike

我有一个这种形式的数据集

Agent ID    Month   values
101 Jan-17 2
101 Feb-17 4
101 Mar-17 3
101 Apr-17 8
101 May-17 12
101 Jun-17 3
101 Dec-17 1
102 Jan-17 2
102 Feb-17 3
102 Mar-17 7
102 Apr-17 3
102 May-17 2
102 Jun-17 11
102 Sep-17 2
102 Oct-17 2
102 Nov-17 1
102 Dec-17 4

我希望它变成这个形状

Agent ID    Month   values  Jan-17  Feb-17  Mar-17  Apr-17  May-17  Jun-17  Sep-17  Oct-17  Nov-17  Dec-17
101 Jan-17 2 2 4 3 8 12 3 0 0 0 1
101 Feb-17 4 2 4 3 8 12 3 0 0 0 1
101 Mar-17 3 2 4 3 8 12 3 0 0 0 1
101 Apr-17 8 2 4 3 8 12 3 0 0 0 1
101 May-17 12 2 4 3 8 12 3 0 0 0 1
101 Jun-17 3 2 4 3 8 12 3 0 0 0 1
101 Dec-17 1 2 4 3 8 12 3 0 0 0 1
102 Jan-17 2 2 3 7 3 2 11 2 2 1 4
102 Feb-17 3 2 3 7 3 2 11 2 2 1 4
102 Mar-17 7 2 3 7 3 2 11 2 2 1 4
102 Apr-17 3 2 3 7 3 2 11 2 2 1 4
102 May-17 2 2 3 7 3 2 11 2 2 1 4
102 Jun-17 11 2 3 7 3 2 11 2 2 1 4
102 Sep-17 2 2 3 7 3 2 11 2 2 1 4
102 Oct-17 2 2 3 7 3 2 11 2 2 1 4
102 Nov-17 1 2 3 7 3 2 11 2 2 1 4
102 Dec-17 4 2 3 7 3 2 11 2 2 1 4

最佳答案

我认为首先是透视,然后合并

df.Month=pd.to_datetime(df.Month,format='%b-%y').dt.strftime('%Y-%m')
s=df.pivot(*df.columns).fillna(0).reset_index()
df=df.merge(s)
df
Out[876]:
AgentID Month values ... 2017-10 2017-11 2017-12
0 101 2017-01 2 ... 0.0 0.0 1.0
1 101 2017-02 4 ... 0.0 0.0 1.0
2 101 2017-03 3 ... 0.0 0.0 1.0
3 101 2017-04 8 ... 0.0 0.0 1.0
4 101 2017-05 12 ... 0.0 0.0 1.0
5 101 2017-06 3 ... 0.0 0.0 1.0
6 101 2017-12 1 ... 0.0 0.0 1.0
7 102 2017-01 2 ... 2.0 1.0 4.0
8 102 2017-02 3 ... 2.0 1.0 4.0
9 102 2017-03 7 ... 2.0 1.0 4.0
10 102 2017-04 3 ... 2.0 1.0 4.0
11 102 2017-05 2 ... 2.0 1.0 4.0
12 102 2017-06 11 ... 2.0 1.0 4.0
13 102 2017-09 2 ... 2.0 1.0 4.0
14 102 2017-10 2 ... 2.0 1.0 4.0
15 102 2017-11 1 ... 2.0 1.0 4.0
16 102 2017-12 4 ... 2.0 1.0 4.0
[17 rows x 13 columns]

更多信息

s
Out[878]:
Month AgentID 2017-01 2017-02 ... 2017-10 2017-11 2017-12
0 101 2.0 4.0 ... 0.0 0.0 1.0
1 102 2.0 3.0 ... 2.0 1.0 4.0
[2 rows x 11 columns]

关于python - 在Python中转置/ reshape 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56140577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com