我有一张桌子
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