Home > Blockchain >  How to change the dataframe shape from multiple rows to a single row in Python?
How to change the dataframe shape from multiple rows to a single row in Python?

Time:06-23

I have this datafarme;

df = pd.DataFrame({'image_id':'490.png', 'labels':['logo_sony', 'text', 'text', 'object_headphone', 'text', 'button']})

It returns a 6 rows and 2 columns dataframe.

   image_id   labels
0   490.png  logo_sony
1   490.png  text
2   490.png  text
3   490.png  object_headphone
4   490.png  text
5   490.png  button

How can I make it one row with two columns,like bellow

    image_id          labels
0   490.png         'logo_sony', 'text', 'text', 'object_headphone', 'text', 'button'

Thank you

CodePudding user response:

A simple solution is to use a string instead of a list as labels value:

labels = "'logo_sony', 'text', 'text', 'object_headphone', 'text', 'button'"
df = pd.DataFrame({'image_id':['490.png'], 'labels':labels})
print(df)

Output

  image_id                                             labels
0  490.png  'logo_sony', 'text', 'text', 'object_headphone...

CodePudding user response:

You can convert the list in your input dict to a space separated str and read that in -

df = pd.DataFrame({k: [' '.join(v)] if isinstance(v, list) else [v] for k, v in d.items()})

Output

  image_id                                            labels
0  490.png  logo_sony text text object_headphone text button
  • Related