Python Pandas DataFrame.empty
Pandas DataFrame是一个二维的大小可变的,可能是异质的表格数据结构,有标记的axis(行和列)。算术操作在行和列的标签上对齐。
它可以被认为是一个类似于Dict的系列对象的容器。这是Pandas的主要数据结构。Pandas DataFrame.empty属性检查数据框架是否为空。如果数据框架是空的,它返回True,否则在Python.Net中返回False。
在这篇文章中,我们将看到如何检查Pandas DataFrame是否为空。
Pandas – 检查DataFrame是否为空
语法: DataFrame.empty
参数: None
返回:布尔类型
创建一个数据框架
# importing pandas as pd
import pandas as pd
# Creating the DataFrame
df = pd.DataFrame({'Weight':[45, 88, 56, 15, 71],
'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],
'Age':[14, 25, 55, 8, 21]})
# Create the index
index_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']
# Set the index
df.index = index_
# Print the DataFrame
print(df)
输出 :
使用DataFrame.empty属性
示例 1:
这里我们将使用DataFrame.empty属性来检查给定的数据框架是否为空。
# check if there is any element
# in the given dataframe or not
result = df.empty
# Print the result
print(result)
输出 :
False
注意:我们可以在输出中看到,DataFrame.empty属性返回False,表明给定的数据框架不是空的。
示例 2:
现在我们将使用DataFrame.empty属性来检查给定的数据框架是否为空。
# importing pandas as pd
import pandas as pd
# Creating an empty DataFrame
df = pd.DataFrame(index = ['Row_1', 'Row_2',
'Row_3', 'Row_4',
'Row_5'])
# Print the DataFrame
print(df)
# check if there is any element
# in the given dataframe or not
result = df.empty
# Print the result
print(result)
输出 :
True
注意:我们可以在输出中看到,DataFrame.empty属性已经返回True,表明给定的数据框架是空的。
使用 dataframe.shape[0]
这里我们使用的是数据框架的形状,它给我们提供了行数和列数的计数。
import pandas as pd
import numpy as np
# Creating an empty DataFrame
df = pd.DataFrame({'A' : [np.nan]})
print(df.dropna().shape[0] == 0)
输出 :
True