使用另一个数据框的索引创建一个空数据框 [英] Create an empty data frame with index from another data frame
本文介绍了使用另一个数据框的索引创建一个空数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含多个列和行的数据框 df1.简单例子:
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
我想创建一个空数据框df2,然后添加带有计算结果的新列.
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
...添加两个新列:
df2["results1"],df2["results2"]=df1["T1"]*df["T2"]*3,df1["T2"]+100
有没有更好/更安全/更快的方法来做到这一点?是否可以创建一个空的数据框 df2 并且只从 df1 复制索引?
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 = pd.DataFrame(index=df1.index)
这将创建一个没有列而只有一个索引的 DataFrame,并且它将与 df1 中的索引相同.
This will create a DataFrame with no columns but just an index, and it will be the same index as in the df1.
这篇关于使用另一个数据框的索引创建一个空数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文