Skip to main content
 首页 » 编程设计

python之适用于无的 Pandas 分类系列

2024年10月01日7fff_TT

下面的代码

df = pd.DataFrame({ 
    'animals': 'kot pies lis kot'.split() + [None] 
}, dtype='category') 
 
df.animals.apply(len) 

无返回 4:

0    3 
1    4 
2    3 
3    3 
4    4 
Name: animals, dtype: int64 

它是 pandas 中的错误还是“功能”?

请您参考如下方法:

这似乎是错误,但更好的是使用 str.len正确处理 NaN 和 None:

print (df.animals.str.len()) 
0    3.0 
1    4.0 
2    3.0 
3    3.0 
4    NaN 
Name: animals, dtype: float64 

对于非分类apply(len)返回错误:

df = pd.DataFrame({ 
    'animals': 'kot pies lis kot'.split() + [None] 
}) 
 
print (df.animals.apply(len)) 

TypeError: object of type 'NoneType' has no len()

但是 str.len 工作得很好:

print (df.animals.str.len()) 
0    3.0 
1    4.0 
2    3.0 
3    3.0 
4    NaN 
Name: animals, dtype: float64