简体   繁体   中英

Pandas convert columns to rows

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

在此处输入图像描述

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

在此处输入图像描述

I tried this code which gave me an error:

在此处输入图像描述

EDIT:

I have tried Marcel's suggestion, the output it gave is this: 在此处输入图像描述

The "label" column is a group or class of file paths. I want to convert it in such a way it fits this function: tf.Keras.preprocessing.image.flow_from_dataframe in categorical

Thanks in advance to all for helping me out.

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

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)

I've found what was wrong, I misunderstood y_col and x_col in tf.Keras.preprocessing.image.ImageDataGenerator.flow_from_dataframe . Thanks to all of you for your contributions. Your answers are all correct in different ways. Thanks again Marcel h and user16714199 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM