我有一个类似的表
key Name
1 snake
2 panda
3 parrot
4 catipie
5 cattie
现在我想找到每行第一个字符的出现次数,并按降序排序,如果有平局,它应该按词汇顺序排序,所以我的输出看起来像:
c 2
p 2
s 1
通过索引str[0]
选择第一个值,并通过value_counts
:计数
s = df['Name'].str[0].value_counts()
print (s)
p 2
c 2
s 1
Name: Name, dtype: int64
对于DataFrame
,将rename_axis
与reset_index
:相加
df = df['Name'].str[0].value_counts().rename_axis('first').reset_index(name='count')
print (df)
first count
0 p 2
1 c 2
2 s 1
如有必要,按字母对相同计数进行排序,添加sort_values
:
df = df.sort_values(['first','count'], ascending=[True, False])
print (df)
first count
1 c 2
0 p 2
2 s 1
系列:
s = df.set_index('first')['count']
print (s)
first
c 2
p 2
s 1
Name: count, dtype: int64
上次使用to_string
:
print (s.to_string(header=None))
c 2
p 2
s 1