简体   繁体   English

如何转置并添加具有从其中一列引用的值的新列

[英]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.

相关问题 从一列的值向DataFrame添加新列 - Add new columns to DataFrame from the value of one column 如何将多列转置为python中的一列 - How to transpose multiple columns to be in one column in python 如何将一列的值除以前一行的列(而不是同一列),并将结果作为新维度添加到numpy数组中? - How to divide one columns value by a previous rows column(not the same column) and add the result as a new dimension to a numpy array? 如何将一列添加到基于另一个列值的数据框中? - How can I add a column to a dataframe that is based on another columns value? 如何从 dataframe 中包含列表的列创建新列 - How can I create a new columns from a column with lists in a dataframe 如何根据键列将新行从 dataframe 添加到另一行 - How can I add new rows from a dataframe to another one based on key column 如何在列数据库/ PYTHON上添加新值 - How Can I Add New Value On Column Database /PYTHON 如何在新列中分隔列 - How can I separate a column in new columns 如何将新列添加到使用功能检查数据是否符合特定条件的函数的数据框? - How can I add a new column to dataframe that uses a function to check if values from two columns fit specific criteria? Pandas dataframe,如何按多列分组并为特定列应用总和并添加新的计数列? - Pandas dataframe, how can I group by multiple columns and apply sum for specific column and add new count column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM