[英]How can I transpose and add a new column with a value referred from one of the columns
I am reading a csv file with the below dataframe:我正在阅读带有以下 dataframe 的 csv 文件:
0 Type Jan-15 Feb-15 Mar-15 Apr-15 May-15 Jun-15
1 Staff 1 3 4 2 2 1
2 Business 2 1 2 3 2 2
3 Parking 1 4 3 3 1 1
My end goal is 1) to transpose the df and 2) to add a quarter column;我的最终目标是 1)转置 df 和 2)添加四分之一列; something along this line
沿着这条线的东西
Type Staff Business Parking quarter
Jan-15 1 2 1 q1
Feb-15 3 1 4 q1
Mar-15 4 2 3 q1
Apr-15 2 3 3 q2
May-15 2 2 1 q2
Jun-15 1 2 1 q2
So far I transposed using this到目前为止,我使用这个转置
dft = df.set_index('Type').transpose()
However I'm struggling with adding the quarter column and filling in the quarter.但是,我正在努力添加季度列并填写季度。 I've given this a try with no success
我已经尝试过了,但没有成功
dft['quarter'] = dft['Type'].str.extract(r'(Jan|Feb|Mar|Apr|May|Jun)').map({'Jan':'Q1', 'Feb':'Q1','Mar':'Q1','Apr':'Q2','May':'Q2','Jun':'Q2'})
Any help of what I've done wrong?对我做错了什么有帮助吗? Any suggestions?
有什么建议么? Thanks!
谢谢!
It seems Type
is index not column name似乎
Type
是索引而不是列名
dft['quarter'] = dft.index.str.extract(r'(Jan|Feb|Mar|Apr|May|Jun)')[0].map({'Jan':'Q1', 'Feb':'Q1','Mar':'Q1','Apr':'Q2','May':'Q2','Jun':'Q2'}).values
Type Staff Business Parking quarter
Jan-15 1 2 1 Q1
Feb-15 3 1 4 Q1
Mar-15 4 2 3 Q1
Apr-15 2 3 3 Q2
May-15 2 2 1 Q2
Jun-15 1 2 1 Q2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.