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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With