gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:34:48 25 4
gpt4 key购买 nike

我有一个像这样的表

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_axisreset_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

关于python - 在python 3中查找表中名称第一个字符的频率分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53301512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com