1

I would like to ask you on how to transpose the dataframe in pandas?

Here is the code:

df = pd.DataFrame([[[1, 2, 3]], [[4, 5, 6]]], index=['step1', 'step2'], columns=['process'])

df

        process
step1   [1, 2, 3]
step2   [4, 5, 6]
df1 = df['process'].apply(pd.Series).rename(columns=lambda x: f'sp {x+1}')

df1

        sp 1    sp 2    sp 3
step1   1       2       3
step2   4       5       6
out = pd.concat([df1], keys=['process'], axis=1)

out

              process
        sp 1    sp 2    sp 3
step1   1       2       3
step2   4       5       6

How to transpose the dataframe from (step x sample) becomes (sample x step) like this?

         process
      step1   step2    
sp 1    1       4
sp 2    2       5
sp 3    3       6

Thank you in advance.

1 Answers1

0

You juste need to add the Transpose method :

out = pd.concat([df1.T], keys=['process'], axis=1)

In a chained manner, without creating df1, it gives this :

out = (
        df['process']
           .apply(pd.Series)
           .rename(columns= lambda c: f'sp {c+1}')
           .pipe(lambda d: pd.concat([d.T], keys=['process'], axis=1))
      )

Another approach,

out = (
        df["process"]
            .astype(str)
            .str.strip("[]")
            .str.split(",", expand=True)
            .rename(columns=lambda c: f'sp {c+1}')
            .pipe(lambda d: pd.concat([d.T], keys=['process'], axis=1))
       )

# Output :

print(out)

     process      
       step1 step2
sp 1       1     4
sp 2       2     5
sp 3       3     6
Timeless
  • 22,580
  • 4
  • 12
  • 30