gpt4 book ai didi

python - Pandas:根据另一列的值对一列中的单词数进行排序

转载 作者:行者123 更新时间:2023-12-01 01:57:52 24 4
gpt4 key购买 nike

我有两列:df[upvotes]df[headline]。 headers 列包含带有标题字符串的行,upvotes 列仅包含带有整数的行。

使用 pandas,我想找出标题中哪些单词获得最多的赞成票。

最好的方法是什么?

到目前为止,我已经有了这个,但是 apply 方法正在将一系列传递给 x,所以显然我不明白它是如何工作的。

df.groupby('upvotes')['headline'].apply(lambda x: len(x.split(' '))).sort_index(ascending=False)

前5行数据:

   upvotes                                           headline                  
0 1 Software: Sadly we did adopt from the construc...
1 1 Google’s Stock Split Means More Control for L...
2 1 SSL DOS attack tool released exploiting negoti...
3 67 Immutability and Blocks Lambdas and Closures
4 1 Comment optimiser la vitesse de Wordpress?

最佳答案

如果我理解您的问题,您可以使用groupby.mean来实现此目的。如果您需要的话,可以替换为 groupby.sum

一般来说,尽可能避免使用 lambda 函数是个好主意。

df = pd.DataFrame({'upvotes': [1, 1, 1, 67, 1],
'headline': ['Software: Sadly we did adopt from the', 'Google’s Stock Split Means More Control for',
'SSL DOS attack tool released exploiting', 'Immutability and Blocks Lambdas and Closures',
'Comment optimiser la vitesse de Wordpress? ']})

df['wordcount'] = df['headline'].str.split().map(len)

df = df.groupby('wordcount', as_index=False)['upvotes'].mean()\
.sort_values('upvotes', ascending=False)

print(df)

# wordcount upvotes
# 0 6 23
# 1 7 1

关于python - Pandas:根据另一列的值对一列中的单词数进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49961846/

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