Skip to content
Advertisement

How to combine multiple rows into one row WITHOUT group by in Python Pandas?

I tried searching it on stack overflow, and I got a lot of similar titles but the problem isn’t quite the same (it appears very different). Also, read some of the documentation (not all from Pandas) but couldn’t find any method to do this.

Suppose I have a dataframe like: enter image description here

How do I combine this into one row in Pandas? That is, how can I have one line with the values:

0.000181 0.10139 0.009276 ... 0.0043778 ... 0.001094 0.004550 0.002879 ... 0.000435 0.003431 ...

Literally that’s all I was trying to find. These other things are suggesting I do a group by, or a join, or something.

Advertisement

Answer

rows=[] #initiate a list to store each row

for i in range(len(df)):
    temp=df.loc[[i]] #extract each row
    temp.columns=np.arange(i*len(temp.columns),(i+1)*len(temp.columns)) #rename column of each row
    temp.reset_index(drop=True, inplace=True) #drop index
    rows=rows+[temp] #add it to the list of rows

output=pd.concat(rows,axis=1) #concat the list of rows by column
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement