我该如何计算“'”这样的特殊字符?在熊猫的DataFrame中的每一列?

时间:2020-04-30 20:55:31

标签: python pandas special-characters

这似乎是一个容易和简单的任务,但是我正在寻找基本而全面的答案,以对我的缺失值进行计数,以将其编码为“?”字符。

我的数据: enter image description here

我希望我的回答是这样的:

drive_wheels 0
engine_location 0
engine_type 0
num_of_cylinders 0
fuel_system 0
bore 4
stroke 4

我尝试过这个:

 for i in data.columns:
           counter = 0
           if data[i].dtype == '?':
                counter += 1
           else:
                counter = 1
 print(i, ' ', str(sum(counter)))

如果有人可以帮助我,我将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

您将counter变量包含在循环中,这意味着每个循环都将其重置为0。所有要做的就是像这样将其移到循环外;

counter = 0
for i in data.columns:
    if data[i].dtype == '?'
        counter += 1

答案 1 :(得分:0)

Apply是每个列equal ?的函数,并将True结果相加

data.apply(lambda serie: serie.eq('?').sum(), axis=0)

如果由于某种原因内容不严格等于?(例如,它包含其他空格),请使用contains方法:

data.apply(lambda serie: serie.str.contains('\?').sum(), axis=0)