Skip to content Skip to sidebar Skip to footer

How Can I Convert Columns To Rows In Pandas?

I have something like this: Values Time 22 0 45 1 65 2 78 0 12 1 45 2 and I want this: Time 0 1 2 Val1 22

Solution 1:

This is pivot creating the index with cumcount

df['idx'] = 'Val' + (df.groupby('Time').cumcount()+1).astype(str)
df.pivot(index='idx', columns='Time', values='Values').rename_axis(None)

Output:

Time012
Val1  224565
Val2  781245

Solution 2:

You need to transpose your array/matrix.

Use

list(map(list, zip(*l)))

where list is your list

Solution 3:

If your time-delta is constant, ordered and has no missing values:

DELTA = 3
new_values = [df['Values'].iloc[i*DELTA:i*DELTA+DELTA].values.transpose() for i inrange(int(len(df)/DELTA))]
df_new = pd.DataFrame(new_values , index=['Val'+str(i+1) for i inrange(len(new_values ))])

print(df_new)
         012
Val1    224565
Val2    781245

Not a pretty solution, but maybe it helps. :-)

Post a Comment for "How Can I Convert Columns To Rows In Pandas?"