Create an empty data frame with index from another data frame

PythonIndexingPandas

Python Problem Overview


I've got a data frame df1 with multiple columns and rows. Simple example:

    TIME T1  T2 
       1 10 100
       2 20 200
       3 30 300

I'd like to create an empty data frame df2 and later on, add new columns with the calculation results.

For this moment my code looks like this:

     df1=pd.read_csv("1.txt",index_col="TIME")

     df2=df1.copy()[[]] #copy df1 and erase all columns

...adding two new columns:

     df2["results1"],df2["results2"]=df1["T1"]*df["T2"]*3,df1["T2"]+100

Is there any better/safer/faster way to do this ? Is it possible to create an empty data frame df2 and only copy index from df1 ?

Python Solutions


Solution 1 - Python

df2 = pd.DataFrame(index=df1.index)

This will create a DataFrame with no columns but just an index, and it will be the same index as in the df1.

Solution 2 - Python

It's better to set index as df1.index.copy()

df2 = pd.DataFrame(index=df1.index.copy())

You can use df1.index is df2.index to check whether they are the same object

Solution 3 - Python

You can also assign the index of a dataframe to another dataframe directly.

df2.index=df1.index

Solution 4 - Python

You can use this short code:

df2=df1[[]].copy()

Solution 5 - Python

To avoid geting all the NaN after the concat add the index to it.

df1 = pd.DataFrame(x1.toarray(),index=simpledf.index, columns=v.get_feature_names())

When defining the new dataframe with X transformed use the same index as the original dataframe.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichalView Question on Stackoverflow
Solution 1 - PythonViktor KerkezView Answer on Stackoverflow
Solution 2 - PythonwaitingkuoView Answer on Stackoverflow
Solution 3 - PythonAnandView Answer on Stackoverflow
Solution 4 - PythonPaulo PintoView Answer on Stackoverflow
Solution 5 - PythonRPeneluppiView Answer on Stackoverflow