在Pandas Column中计算数字os特定字符串

时间:2017-12-22 08:04:58

标签: python pandas

如何计算pandas列中特定字符串的数量? 我想得到它相对于pandas列中字符串总数的百分比。

1 个答案:

答案 0 :(得分:2)

我相信你需要检查字符串a比较和mean的布尔掩码:

print (df['col'].eq('a').mean())
#same as
#print ((df['col'] == 'a').mean())

对于所有值value_counts

print (df['col'].value_counts(normalize=True))

样品:

df = pd.DataFrame({'col':list('aaabbc')})
print (df)
  col
0   a
1   a
2   a
3   b
4   b
5   c

print (df['col'].eq('a').mean())
0.5

print (df['col'].value_counts(normalize=True))
a    0.500000
b    0.333333
c    0.166667
Name: col, dtype: float64

编辑:

如果None列中的value_count s函数首先丢弃它:

df = pd.DataFrame({'col':['a','a','a','b','b','c',None]})
print (df)
    col
0     a
1     a
2     a
3     b
4     b
5     c
6  None

print (df['col'].eq('a').mean())
0.428571428571

#first drop NaN/Nones and then normalize
print (df['col'].value_counts(normalize=True))
a    0.500000
b    0.333333
c    0.166667
Name: col, dtype: float64

#convert None/None to string for count it
print (df['col'].astype(str).value_counts(normalize=True))
a       0.428571
b       0.285714
None    0.142857
c       0.142857
Name: col, dtype: float64
相关问题