python - 如果没有某些特定值,则计算数据帧列中的行数

标签 python python-3.x pandas dataframe

您好,有一个多列数据框,并且想要打印列行的总和,如果这些行不是 nan-

Col1   Col2   Col3    
this   nan     1
that    ?      2
those  this    5
these  that    2
there   -      1 

我想要的结果是

print df['Col2].count()  # Im missing the not ( nan or ? or - ) part here
2

最佳答案

Series.notna 创建的链罩通过 Series.isin 进行反向检查成员资格:

mask = df['Col2'].notna() & ~df['Col2'].isin(['?','-', 'nan'])
#if no missing values only strings nan
#mask = ~df['Col2'].isin(['?','-', 'nan'])
print (mask.sum())
2

详细信息:

print (mask)
0    False
1    False
2     True
3     True
4    False
Name: Col2, dtype: bool

关于python - 如果没有某些特定值,则计算数据帧列中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59156140/

相关文章:

python - 从 subprocess.Popen 进行流式传输并使用两个子命令时出现死锁

python - Pandas df.index.strftime ('%H' )

python - 文本小部件 tkinter

python - 寻求帮助,今天刚开始接触Python。 (3.0)

python - Chainer 中加载的神经网络层的梯度

python - 为什么不能在没有额外的 `import` 语句的情况下引用似乎由解释器自动加载的模块?

python - 将值列表转换为 python 中的时间序列

python - Count_values 具有 where 条件来计算一列相对于其他列的值

python - 在子字符串上加入 pandas 数据框

python - 条件随机数生成器 python numpy