• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Add multiple empty rows at beginning of a populated Dataframe with Python

Resolved: Add multiple empty rows at beginning of a populated Dataframe with Python

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I want to add multiple empty rows at start of my dataframe. I have tried using list but it dosen’t seem to return optimum result:
Example df:
Col1 col2 col3 col4
One Two Three four
2 4 5 8

Desired df:
Col1 col2 col3 col4
One Two Three four
2 4 5 8

Column names should also start from the nth row, I want to add n empty rows at the beginning of my Dataframe.

Answer:

I’m not sure why you would want to do this but I did it by splitting up the original dataframe into a dataframe with a row of the column names and a separate dataframe of the data. I then created a dataframe of nans to be the blank rows and joined the 3 together. You will need to import numpy for this.
I created a variable no_cols to be the number of columns in the dataframe and no_empty_rows to be how many empty rows to simplify code:
Then I turned the columns into their own dataframe, with 1 row which is the column names, and headers as np.nan:
Next I renamed the columns in the original dataframe to nan:
Then I created a new dataframe of nans, with 6 blank rows (this can be changed):
You can then append together all 3. First I put the columns and data of df back together and reset their index, then append that to df_empty_rows:
Full code:

If you have better answer, please add a comment about this, thank you!

dataframe numpy pandas python-3.x
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Use Svelte Component as Slot

26/03/2023

Resolved: Vaadin 14.9 – Redirect on Session Destroy Event

26/03/2023

Resolved: How to separate multiple answers in one column, for multiple columns, by creating extra columns

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.