【问题标题】:Pandas: Sort number of words in one column by the values of another熊猫:按另一列的值对一列中的单词数进行排序
【发布时间】:2023-04-04 04:04:01
【问题描述】:

我有两列:df[upvotes]df[headline]。标题列包含带有标题字符串的行,而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?      

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-03-24
      • 2020-05-12
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 2022-01-25
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多