【问题标题】:Count number of times observation appears row wise pandas? [duplicate]计数观察出现行明智的熊猫的次数? [复制]
【发布时间】:2021-08-10 15:35:07
【问题描述】:

如果我有这样的数据框:

Area Favorite Fruit
UT Banana
TN Grape
VT Banana
AZ Banana
CA Cherry

我想插入一列,计算水果在 df 中出现的次数,如下所示:

Area Favorite Fruit Fruit Count
UT Banana 3
TN Grape 1
VT Banana 3
AZ Banana 3
CA Cherry 1

尝试在 python 中执行此操作。

【问题讨论】:

标签: python pandas


【解决方案1】:

使用transform('size'):

df['Fruit Count'] = df.groupby('Favorite Fruit')['Favorite Fruit'].transform('size')

【讨论】:

    【解决方案2】:

    试试value_counts + reindex

    df['Fruit Count'] = df['Favorite Fruit'].value_counts()\
                       .reindex(df['Favorite Fruit']).values
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      • 2019-05-13
      • 2022-08-16
      相关资源
      最近更新 更多