Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create empty Dataframe with same dimensions as another?

Tags:

python

pandas

I have searched a bit, but can not find a good answer. I want to create an empty dataframe with same dimensions as another dataframe so I can add new columns. Today I create an empty dataframe filled with zeroes, and then I delete the zero column. I hope there is a better way, but can not find the answer. Can someone help me?

I do like this today and it works, but it is very ugly.

df_copy = pandas.DataFrame(numpy.zeros(len(df_original.index)))  df_copy = df_copy.drop([0],axis=1)  

And now I can add new columns as I process data. So basically I want an empty dataframe with same dimensions as another dataframe.

df_copy["price"] = pricesList df_copy["size"] = sizesList 

EDIT: Another closely related question: how do I create an empty Dataframe with dimensions mxn? I have got the answer below how to create an empty dataframe with dimensions 1xn, which is by setting the index. But how do I create an empty nxm dataframe filled with zeroes? The reason I am asking, is because I suspect(?) it is faster to create a zero filled dataframe, and then replace each element as needed. The alternative is to create an empty dataframe with dimensions 1xn and then add columns as needed - which I am told is slow. So it might be faster to create an empty dataframe with nxm dimensions and then replace elements as needed (by copying a list to each column). Say a column has 100 rows, and I create a sublist with 25 rows, so I just copy this list to the correct subcolumn, and repeat. This is faster than adding a new column?

like image 943
Orvar Korvar Avatar asked Apr 21 '14 10:04

Orvar Korvar


People also ask

How do you create an empty DataFrame from another DataFrame in Python?

First, you need to get the list of columns from the dataframe df using df. columns . Then, you can create an empty dataframe by passing this column list to columns parameter.

How do you create an empty DataFrame with rows and columns in R?

One simple approach to creating an empty DataFrame in the R programming language is by using data. frame() method without any params. This creates an R DataFrame without rows and columns (0 rows and 0 columns).


2 Answers

Creating an empty dataframe with the same index and columns as another dataframe:

import pandas as pd df_copy = pd.DataFrame().reindex_like(df_original) 
like image 58
kadee Avatar answered Sep 19 '22 15:09

kadee


For anyone coming to this page looking to create a dataframe of same columns, same dtypes, and no rows:

import pandas as pd df_copy = df_original.iloc[:0,:].copy() 
like image 26
Ben Saunders Avatar answered Sep 21 '22 15:09

Ben Saunders