Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move every second row to row above in pandas dataframe

Tags:

python

pandas

I have dataframe in this shape:

    A     B     C    D     E 
  213-1  XL   NaN    NaN    NaN
  21   22.0   12   232.0  101.32
  23-0    L   NaN    NaN    NaN
  12     23   12   232.2    NaN
  31-0   LS   NaN    NaN    NaN
  70     70   23     NaN   21.22

I would like to move every second row of that dataframe to the row above so that there are only combined rows left as seen in the expected result:

     ID   Name     A     B    C     D     E
   213-1    XL    21   22.0  12  232.0  101.32
   23-0      L    12     23  12  232.2     NaN
   31-0     LS    70     70  23    NaN   21.22

Is it possible to do with Pandas?

like image 607
Alex T Avatar asked Nov 12 '19 13:11

Alex T


People also ask

How do you shift rows in pandas?

shift() If you want to shift your column or subtract the column value with the previous row value from the DataFrame, you can do it by using the shift() function. It consists of a scalar parameter called period, which is responsible for showing the number of shifts to be made over the desired axis.

How do you get top 5 rows in pandas?

Select first N Rows from a Dataframe using head() function In Python's Pandas module, the Dataframe class provides a head() function to fetch top rows from a Dataframe i.e. It returns the first n rows from a dataframe. If n is not provided then default value is 5.

How do I add a row to a specific position in pandas?

The easiest way to add or insert a new row into a Pandas DataFrame is to use the Pandas . append() method. The . append() method is a helper method, for the Pandas concat() function.


1 Answers

I would use concat:

new_df = pd.concat((df.iloc[::2, :2].reset_index(drop=True), 
                    df.iloc[1::2].reset_index(drop=True)),
                   axis=1)

# rename
new_df.columns = ['ID', 'Name'] + new_df.columns[2:].to_list()

Output:

      ID Name   A     B     C      D       E
0  213-1   XL  21  22.0  12.0  232.0  101.32
1   23-0    L  12    23  12.0  232.2     NaN
2   31-0   LS  70    70  23.0    NaN   21.22
like image 154
Quang Hoang Avatar answered Oct 14 '22 13:10

Quang Hoang