pandas描述全部数据的情况(空值个数,类别个数,数据类型)

如果想在pandas中查看数据情况,我们一般使用describe方法

df = pd.DataFrame({'Yes': [50, 21, 53, 70, 21], 'No': [131, 2, 98, 1, 3],'not':['1','s',1,2,3]})
print(df.describe())

输出为

             Yes          No
count   5.000000    5.000000
mean   43.000000   47.000000
std    21.482551   62.717621
min    21.000000    1.000000
25%    21.000000    2.000000
50%    50.000000    3.000000
75%    53.000000   98.000000
max    70.000000  131.000000

可见,describe只对数值数据有效,对categorical数据无效,如果我们想要对所有的数据分析,不妨自己写一个简单的函数

def get_statistics(df:pd.DataFrame):
    assert len(df.index) != 0 # 断言不为空
    
    null_series = df.isnull().sum() # 空值个数
    unique = df.nunique()           # 类别个数
    type_series = df.dtypes         # 数据类型
    
    result = pd.DataFrame({'null':null_series,'unique':unique,'type':type_series})
    print(result)
    shape = df.shape
    print('this dataFrame with {} rows x {} columns'.format(shape[0],shape[1]))

以泰坦尼克号数据集中的训练集为例

df = pd.read_csv('train.csv')
get_statistics(df)

输出

             null  unique     type
PassengerId     0     891    int64
Survived        0       2    int64
Pclass          0       3    int64
Name            0     891   object
Sex             0       2   object
Age           177      88  float64
SibSp           0       7    int64
Parch           0       7    int64
Ticket          0     681   object
Fare            0     248  float64
Cabin         687     147   object
Embarked        2       3   object
this dataFrame with 891 rows x 12 columns

可以看到,数据最简单的情况已经拿到了。当然,我们还可以把get_statistics和describe的结果进行合并,但是由于包含的列不一样,输出时categorical数据会有几列是空的,不太美观。而我们的get_statistics函数统计的是更一般的特征,对数据集有了一些把握。

如果我们还要更细粒度的数据类型分割,不妨去这里(doge)

更细粒度的数据类型分割


版权声明:本文为RuGe_Lee原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。