创建一个空数据框架,其中包含来自另一个数据框架的索引

我得到了一个包含多个列和行的数据帧 Df1:

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

我想创建一个空的数据帧 Df2,稍后,添加新的列与计算结果。

目前,我的代码如下所示:

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


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

新增两栏:

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

有没有更好/更安全/更快的方法来做这件事? 是否可以创建一个空的数据帧 df2,并且只从 df1复制索引?

150360 次浏览
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.

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

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

df2.index=df1.index

You can use this short code:

df2=df1[[]].copy()

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.