在python3中查找表中名称的第一个字符的频率分布

2024-04-29 20:12:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有张桌子

key Name
 1   snake
 2   panda
 3   parrot
 4   catipie
 5   cattie

现在我想找出每行第一个字符出现的次数,并按降序排序,如果有平局,应该按词法顺序排序,因此我的输出如下:

^{pr2}$

Tags: keyname排序顺序字符次数pandaparrot
1条回答
网友
1楼 · 发布于 2024-04-29 20:12:02

通过索引str[0]选择第一个值并按^{}计数:

s = df['Name'].str[0].value_counts()
print (s)
p    2
c    2
s    1
Name: Name, dtype: int64

对于DataFrame添加^{}^{}

^{pr2}$

如有必要,按字母对同一计数进行排序^{}

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

上次使用^{}

print (s.to_string(header=None))
c    2
p    2
s    1

相关问题 更多 >