How to reverse a 2-dimensional table (DataFrame) into a 1 dimensional list using Pandas?

前端 未结 3 1610
既然无缘
既然无缘 2020-12-28 19:57

I am looking in Python/Pandas for a tip that reverses a 2-dimension table into 1 dimensional list.

I usually leverage an Excel function to do it, but I believe that

3条回答
  •  Happy的楠姐
    2020-12-28 20:57

    This type of operation could also be done using pd.melt, which unpivots a DataFrame.

    If the DataFrame df looks like this:

      row labels  Tue  Wed  Thu  Sat  Sun  Fri  Mon
    0      Apple   21   39   24   27   37   46   42
    1     Banana   32   50   48   35   21   27   22
    2       Pear   37   20   45   45   31   50   32
    

    Then we select the row_labels column to be our id_var and the rest of the columns to be our values (value_vars). We can even choose the new names for the columns at the same time:

    >>> pd.melt(df, 
                id_vars='row labels', 
                value_vars=list(df.columns[1:]), # list of days of the week
                var_name='Column', 
                value_name='Sum of Value')
    
       row labels   Column   Sum of Value
    0       Apple      Tue             21
    1      Banana      Tue             32
    2        Pear      Tue             37
    3       Apple      Wed             39
    4      Banana      Wed             50
    5        Pear      Wed             20
    ...
    

    The value_vars are stacked below each other: if the column values need to be in a particular order it will be necessary to sort the columns after melting.

提交回复
热议问题