Pandas:按anoth的值对一列中的单词数进行排序

2024-09-29 00:15:42 发布

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

我有两列:df[upvotes]df[headline]。headlines列包含带有标题字符串的行,upvots列只是带有整数的行。在

使用pandas,我想找出标题中哪个词的数量最有利于投票。在

最好的办法是什么?在

到目前为止,apply方法将一个序列传递给x,因此显然我不太理解这是如何工作的。在

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

前5行数据:

^{pr2}$

Tags: 方法字符串标题pandasdf数量序列整数
1条回答
网友
1楼 · 发布于 2024-09-29 00:15:42

如果我理解您的问题,您可以使用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

相关问题 更多 >