Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining rows in a dataframe pandas

Tags:

python

pandas

This is my original DF in pandas.

Dataframe

I've tried to combine the first 5 rows into one row by using: combine_first, but I can't achieve it.

I want this

Also I've followed this answer: How to merge two rows in a dataframe pandas. Any suggestions?

like image 931
user2536844 Avatar asked Sep 13 '26 18:09

user2536844


1 Answers

option 1
pd.DataFrame.bfill

df.bfill().iloc[[0]]

option 2
pd.DataFrame.lookup

pd.DataFrame(
    df.lookup(df.apply(pd.Series.first_valid_index), df.columns),
    df.columns).T

option 3
numpy.argmax

v = df.values
pd.DataFrame(
    v[(~np.isnan(v)).argmax(0), np.arange(v.shape[1])].reshape(1, -1),
    columns=df.columns)

All yield

enter image description here


time testing

enter image description here

like image 84
piRSquared Avatar answered Sep 16 '26 07:09

piRSquared