【问题标题】:Print portion of null value打印空值部分
【发布时间】:2020-12-06 07:42:04
【问题描述】:

我正在使用 Titanic 数据集。我想知道如何从训练集中显示部分空值。

这是我的代码:`

train_count_of_missval_by_col = (train.isnull().sum())
print('----- all columns along with count of missing value')
print(train_count_of_missval_by_col)
print('----only columns which has missing values----')
print(train_count_of_missval_by_col[train_count_of_missval_by_col>0])
print('----only columns which has missing data to total observations----')
print(train_count_of_missval_by_col[train_count_of_missval_by_col>0]/train.shape[])`

不幸的是,代码的最后一行产生了错误。在最后一行添加/编辑什么以使代码正常工作?

【问题讨论】:

  • 您必须返回 train.shape[0]train.shape[1],而不是 train.shape[]train.shape 是一个元组,你试图访问(rows, columns) 的第一个或第二个值,所以[] 会导致错误,因为你没有传递元组中任何值的索引/位置,所以 python /pandas 不知道如何处理该语法,因此您将收到:SyntaxError: invalid syntax。另外,请在将来的问题中包含您的错误,以便人们可以更好地帮助您以及提供示例数据:)。

标签: python pandas null


【解决方案1】:

我不确定是否有针对此的特定操作。 info() 向您显示原始 # 并告诉您总行数,但没有用于 % 的参数。 .info() 也作为 None 类型的对象返回,因此您无法访问该对象的任何数据。

我建议遍历该列并返回 #null 除以总行数,df[col].isnull().sum() / df.shape[0] * 100 并以这样的格式化字符串打印输出:

d = {'Col1': [np.nan, 6, np.nan, 2, np.nan],
     'Col2': [np.nan, 3, 5, np.nan, 9],
     'Col3': [2, 1, 8, np.nan, 9]}
df = pd.DataFrame(d)
for col in df.columns:
    print(col, f'{df[col].isnull().sum() / df.shape[0] * 100} % NULL')

Col1 60.0 % NULL
Col2 40.0 % NULL
Col3 20.0 % NULL

【讨论】:

    猜你喜欢
    • 2019-01-04
    • 2011-11-10
    • 2019-02-22
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    相关资源
    最近更新 更多