I need to combine multiple rows into a single row, that would be simple concat with space
View of my dataframe: tempx value 0 picture1 1.5 1 picture555 1.5 2 picture255 1.5 3 picture365 1.5 4 picture112 1.5
I want the dataframe to be converted like this: (space separated)
tempx values
Expected output:
tempx value
0 picture1 picture555 picture255 picture365 picture112 1.5
or
as a python dict
{1.5:{picture1 picture555 picture255 picture365 picture112}}
What I have tried :
df_test['tempx']=df_test['tempx'].str.cat(sep=' ')
this works but it combines the rows in all the columns like this:
tempx value 0 picture1 picture555 picture255 picture365 picture112 1.5 1 picture1 picture555 picture255 picture365 picture112 1.5 2 picture1 picture555 picture255 picture365 picture112 1.5 3 picture1 picture555 picture255 picture365 picture112 1.5 4 picture1 picture555 picture255 picture365 picture112 1.5
Is there any elegant solution?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use groupby and apply function join :
print df.groupby('value')['tempx'].apply(' '.join).reset_index()
value tempx
0 1.5 picture1 picture555 picture255 picture365 pict...
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0