pandas 如何创建 python 空数据帧,其中 df.empty 结果为 True

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43573983/
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-09-14 03:27:27  来源:igfitidea点击:

how to create python empty dataframe where df.empty results in True

pythonpandasdataframeis-empty

提问by Goofy Gert

How can I create an empty dataframe in python such that the test df.emptyresults True?

如何在 python 中创建一个空数据框以便测试df.empty结果True

I tried this:

我试过这个:

df = pd.DataFrame(np.empty((1, 1)))

and df.emptyresults in False.

df.empty导致False.

回答by Psidom

The simplest is pd.DataFrame():

最简单的是pd.DataFrame()

df = pd.DataFrame()   

df.empty
# True

If you want create a data frame of specify number of columns:

如果要创建指定列数的数据框:

df = pd.DataFrame(columns=['A', 'B'])

df.empty
# True

Besides, an array of shape (1, 1)is not empty (it has one row), which is the reason you get empty = False, in order to create an empty array, it needs to be of shape (0, n):

此外,形状为(1, 1)的数组不为空(它有一行),这就是您得到empty = False的原因,为了创建一个空数组,它需要形状为(0, n)

df = pd.DataFrame(pd.np.empty((0, 3)))

df.empty
# True