如何使用bool值计算列中的行?

时间:2018-03-17 15:37:04

标签: python-3.x pandas dataframe

我有一个数据框users,其中包含三列idusernamepassword

我正在尝试计算password中少于8个字符数的行数。 我的代码:

# Calculating the length of user's passwords
users['length'] = users.password.str.len()

# Flagging the users with too short passwords`

users['too_short'] = pd.cut(users['length'], bins=[0,7,300], labels=[True,False])

print (users[users['too_short'].any(1)])

# Counting and printing the number of users with too short passwords
print(users['too_short'].count())

# Taking a look at the 12 first rows
users.head(12)

它出现以下错误:

TypeError: Categorical cannot perform the operation any

too_short的值为TrueFalse。我试图找到一种方法来计算此列中基于布尔值的行数,但没有运气。

1 个答案:

答案 0 :(得分:1)

试试这个:

users['too_short'] = users['length'] < 7

print(users[users['too_short']])
print(users['too_short'].count())