Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concat empty data frame with another Dataframe in pandas with python

I have an empty dataframe of 14 rows with nan values created as below:

dfs_empty_rows = pd.DataFrame(data=[[np.nan] * len(interm_df.columns)] * 14, columns=[np.nan] * len(interm_df.columns))

I want to concat interm_df, which was values with dfs_empty_rows so that the forst 14 rows are blank in the new dataframe.
I am trying to concat using:

pd.concat([dfs_empty_rows,df], axis=0, ignore_index=True)

But this is giving an error :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

InvalidIndexError: Reindexing only valid with uniquely valued Index objects

How can i concat an empty df with another df with values.

Output should be concat of empty df with values df in order.

>Solution :

IIUC change empty Dataframe constructor with same columns names like df – missing values are default, so not necessary specify – only index:

df = pd.DataFrame({'a':range(4), 'b':range(5, 9)})

dfs_empty_rows = pd.DataFrame(index=range(14), columns=df.columns)
print (dfs_empty_rows)
      a    b
0   NaN  NaN
1   NaN  NaN
2   NaN  NaN
3   NaN  NaN
4   NaN  NaN
5   NaN  NaN
6   NaN  NaN
7   NaN  NaN
8   NaN  NaN
9   NaN  NaN
10  NaN  NaN
11  NaN  NaN
12  NaN  NaN
13  NaN  NaN

df1 = pd.concat([dfs_empty_rows,df], ignore_index=True)
print (df1)
      a    b
0   NaN  NaN
1   NaN  NaN
2   NaN  NaN
3   NaN  NaN
4   NaN  NaN
5   NaN  NaN
6   NaN  NaN
7   NaN  NaN
8   NaN  NaN
9   NaN  NaN
10  NaN  NaN
11  NaN  NaN
12  NaN  NaN
13  NaN  NaN
14    0    5
15    1    6
16    2    7
17    3    8
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading