Python 使用另一个数据框的索引创建一个空数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18176933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:05:24  来源:igfitidea点击:

Create an empty data frame with index from another data frame

pythonindexingpandas

提问by Michal

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

我有一个包含多列和多行的数据框df1。简单的例子:

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

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

我想创建一个空的数据框df2,然后再添加带有计算结果的新列。

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 ?

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

采纳答案by Viktor Kerkez

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.

这将创建一个没有列而只有一个索引的 DataFrame,并且它将与 df1 中的索引相同。

回答by waitingkuo

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

最好将索引设置为 df1.index.copy()

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

You can use df1.indexis df2.indexto check whether they are the same object

您可以使用df1.indexisdf2.index检查它们是否是同一个对象

回答by Anand Mohan

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

您还可以直接将数据帧的索引分配给另一个数据帧。

df2.index=df1.index

df2.index=df1.index

回答by Paulo Pinto

You can use this short code:

您可以使用此短代码:

df2=df1[[]].copy()

df2=df1[[]].copy()

回答by RPeneluppi

To avoid geting all the NaNafter the concat add the index to it.

为避免NaN在 concat 之后获得所有内容,请向其中添加索引。

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

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

在定义具有X转换的新数据帧时,使用与原始数据帧相同的索引。