Home > Net >  pandas pivot data Cols to rows and rows to cols
pandas pivot data Cols to rows and rows to cols

Time:01-25

I am using python and pandas have tried a variety of attempts to pivot the following (switch the row and columns)

Example: A is unique

         A       B   C   D     E... (and so on)
     [0] apple   2   22  222
     [1] peach   3   33  333
     [N] ... and so on

And I would like to see

    ?  ?       ?     ?   ... and so on
    A  apple   peach
    B  2       3
    C  22      33
    D  222     333
    E 
    ... and so on

I am ok if the columns are named after the col "A", and if the first column needs a name, lets call it "name"

    name  apple   peach ...
    B     2       3
    C     22      33
    D     222     333
    E 
    ... and so on

CodePudding user response:

Think you're wanting transpose here.

df = pd.DataFrame({'A': {0: 'apple', 1: 'peach'}, 'B': {0: 2, 1: 3}, 'C': {0: 22, 1: 33}})

df = df.T

print(df)

     0       1
A   apple   peach
B   2       3
C   22      33

Edit for comment. I would probably reset the index and then use the df.columns to update the column names with a list. You may want to reset the index again at the end as needed.

df.reset_index(inplace=True)

df.columns = ['name', 'apple', 'peach']

df = df.iloc[1:, :]

print(df)

    name    apple   peach
1   B       2       3
2   C       22      33

CodePudding user response:

try df.transpose() it should do the trick

  •  Tags:  
  • Related