【问题标题】:Pandas: how to count the frequency of words in a column based on another column [duplicate]Pandas:如何根据另一列计算一列中单词的频率[重复]
【发布时间】:2021-12-26 01:07:18
【问题描述】:

我有一个包含 4 列的 csv 文件,其中 column1 是 car_id,column2 是制造商,column3 是 car_year,column4 是汽车型号,如下所示。如果 column2 中的品牌是“福特”,我想使用 pandas 数据框仅计算 coumn4 中的模型。

column 1    column2   column3   column4
 005         Ford      2012      Mustang
 125         Ford      2020      Focus
 223         BMW       2017      X5
 115         Ford      2015      Focus
 566         Kia       2011      ceed

所以输出类似于

model    counts
Mustang  1
Focus    2

任何帮助。谢谢

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以先选择基于column2,然后使用.values_counts()。试试这个:

    >>> df[df['column2'] == 'Ford']['column4'].value_counts()
    

    作为数据框:

    >>> pd.DataFrame(df[df['column2'] == 'Ford']['column4'].value_counts()
                    ).reset_index()\
    .rename(columns={'index':'model', 'column4':'counts'}
    )
        model       counts
    0   Ford        2
    1   Mustang     1
    

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2020-07-28
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      相关资源
      最近更新 更多