Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine multiple rows into a single row with pandas [duplicate]

Tags:

python

pandas

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?

like image 824
Sandeep Raikar Avatar asked Apr 03 '16 23:04

Sandeep Raikar


People also ask

How do I combine DataFrame rows?

We can use the concat function in pandas to append either columns or rows from one DataFrame to another. Let's grab two subsets of our data to see how this works. When we concatenate DataFrames, we need to specify the axis. axis=0 tells pandas to stack the second DataFrame UNDER the first one.

What is the difference between merging and concatenation in pandas?

merge() for combining data on common columns or indices. . join() for combining data on a key column or an index. concat() for combining DataFrames across rows or columns.


1 Answers

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...
like image 164
jezrael Avatar answered Oct 03 '22 01:10

jezrael