Home > Mobile >  Pandas convert columns to rows
Pandas convert columns to rows

Time:09-27

I am a beginner in Data Science and I am trying to pivot this data frame using Pandas:

enter image description here

So it becomes something like this: (The labels should become the column and file paths the rows.)

enter image description here

I tried this code which gave me an error:

enter image description here

CodePudding user response:

I did not understand your question very well, but if you just want to convert columns to rows then you can do

train_df.T

wich means transpose

CodePudding user response:

I think you are looking for something like this:


import pandas as pd

df = pd.DataFrame({
    'labels': ['a', 'a', 'a', 'b', 'b'],
    'pathes' : [1, 2, 3, 4, 5]
})

labels = df['labels'].unique()
new_cols = []
for label in labels:
    new_cols.append(df['pathes'].where(df['labels'] == label).dropna().reset_index(drop=True))
df_final = pd.concat(new_cols, axis=1)

print(df_final)

  • Related