Python 3.x 如何计算熊猫中列中非空元素的数量?
如何获取列中非空元素的总数Python 3.x 如何计算熊猫中列中非空元素的数量?,python-3.x,pandas,Python 3.x,Pandas,如何获取列中非空元素的总数 print(len(newDF.Paid_Off_In_Days).where(newDF.Paid_Off_In_Days != '')) 数据类型为int 我得到一个错误: AttributeError:“int”对象没有属性“where” 如果为空,则表示比较掩码的空字符串,并使用计数True值的sum: print((newDF.Paid_Off_In_Days != '').sum()) 如果为空表示缺少值,请使用: 备选答案: 下面的代码使用正则表达式
print(len(newDF.Paid_Off_In_Days).where(newDF.Paid_Off_In_Days != ''))
数据类型为int
我得到一个错误:
AttributeError:“int”对象没有属性“where”
如果为空,则表示比较掩码的空字符串,并使用计数
True
值的sum
:
print((newDF.Paid_Off_In_Days != '').sum())
如果为空表示缺少值,请使用:
备选答案:
下面的代码使用正则表达式将空格替换为NaN。和熊猫的非钠细胞
# Import library
import pandas as pd
# Create DataFrame
newDF = pd.DataFrame({
'Paid_Off_In_Days':[1, np.nan, 15, ' ', 18, 29]
})
# Regex to replace blanks with NaN
newDF = newDF.replace(r'^\s*$', np.nan, regex=True)
# Get counts
counts = newDF.count()
输出
print(counts)
Paid_Off_In_Days 4
dtype: int64
问题是此列中的某些行为空
sum()
甚至会对空/空白的单元格进行计数。@bibscy-因此缺少值和空字符串?数据类型为int
并且缺少values@bibscy-抱歉,我添加了一个(
不正确,需要打印(newDF.Paid\u Off\u In\u Days.count())
阈值是错误的。它有效。非常感谢
# Import library
import pandas as pd
# Create DataFrame
newDF = pd.DataFrame({
'Paid_Off_In_Days':[1, np.nan, 15, ' ', 18, 29]
})
# Regex to replace blanks with NaN
newDF = newDF.replace(r'^\s*$', np.nan, regex=True)
# Get counts
counts = newDF.count()
print(counts)
Paid_Off_In_Days 4
dtype: int64