Python转置数据集

时间:2018-10-30 03:46:32

标签: python

正在寻找执行此操作的python脚本。下面仅是一个示例,这些值是CPU消耗的秒数。

I have a CSV in the format:

col1    col2   col3    col4  Apr2018   May2018   June2018   July 2018 
-----------------------------------------------------------------
Job1    ABD    dt.com  BU1   45087     67547      876465    987564
Job2    ACS    pl.com  BU2   94768     87658      987689    97678

Now I want to be able to get like this in a dataframe/ Table 

col1    col2   col3    col4  Date      Value
---------------------------------------------
Job1    ABD    dt.com  BU1   Apr2018    45087     
Job1    ABD    dt.com  BU1   May2018    67547
Job1    ABD    dt.com  BU1   June2018   876465
Job1    ABD    dt.com  BU1   July2018   987564

Job2    ACS    pl.com  BU2   Apr2018     94768       
Job2    ACS    pl.com  BU2   May2018     87658
Job2    ACS    pl.com  BU2   June2018    987689
Job2    ACS    pl.com  BU2   July2018      97678

1 个答案:

答案 0 :(得分:0)

   import pandas as pd
   df=pd.read_csv("csv file")
   convert_df = pd.melt(df, id_vars=["col1","col2","col3,"col4"], 
                  var_name="Date", value_name="Value")
   convert_df = convert_df.sort(["col1","col2","col3,"col4"])
   print(convert_df)

在pandas数据框中有功能融合。