有没有办法只复制Pandas DataFrame的结构(而不​​是数据)? [英] Is there a way to copy only the structure (not the data) of a Pandas DataFrame?

查看:527
本文介绍了有没有办法只复制Pandas DataFrame的结构(而不​​是数据)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从某个地方收到一个DataFrame,并想创建另一个具有相同编号和名称的列和行(索引)的DataFrame.例如,假设原始数据帧创建为

I received a DataFrame from somewhere and want to create another DataFrame with the same number and names of columns and rows (indexes). For example, suppose that the original data frame was created as

import pandas as pd
df1 = pd.DataFrame([[11,12],[21,22]], columns=['c1','c2'], index=['i1','i2'])

我通过显式定义列和名称来复制结构:

I copied the structure by explicitly defining the columns and names:

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

我不想复制数据,否则我可以只写df2 = df1.copy().换句话说,在创建df2之后,它必须仅包含NaN元素:

I don't want to copy the data, otherwise I could just write df2 = df1.copy(). In other words, after df2 being created it must contain only NaN elements:

In [1]: df1
Out[1]: 
    c1  c2
i1  11  12
i2  21  22

In [2]: df2
Out[2]: 
     c1   c2
i1  NaN  NaN
i2  NaN  NaN

还有更惯用的方式吗?

推荐答案

这是

That's a job for reindex_like. Start with the original:

df1 = pd.DataFrame([[11, 12], [21, 22]], columns=['c1', 'c2'], index=['i1', 'i2'])

构造一个空的DataFrame并像df1一样对其重新编制索引:

Construct an empty DataFrame and reindex it like df1:

pd.DataFrame().reindex_like(df1)
Out: 
    c1  c2
i1 NaN NaN
i2 NaN NaN   

这篇关于有没有办法只复制Pandas DataFrame的结构(而不​​是数据)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆