【问题标题】:Count appearance of a value in a pandas row计算熊猫行中值的出现次数
【发布时间】:2019-02-22 12:45:00
【问题描述】:

嘿,我目前正在遍历 pandas 中的一个列。 现在我想处理一个值在该列中只出现一次而不是多次出现的情况。 我尝试了几种方法,但都没有奏效。 现在我得到错误: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 我只是尝试首先将所有带有id i 的行过滤到df_path_counter 中,然后我认为它是 if 子句中的行。我不知道为什么它不起作用。 有任何想法吗? 这是我的代码:

df_path = pd.DataFrame([(1, 'Germany'),
               (1, 'France'),
               (1, 'Indonesia'),
               (1, 'France'),
               (2, 'France'),
               (1, 'Germany'),
               (1, 'UK'),
               ],
              columns=['id', 'country']
for i, g in df_path.groupby('id'):
    df_path_counter=df_path.loc[df_path['id'] == i]
    if(df_path_counter.count()<=1):
         #...do sth

【问题讨论】:

  • 使用value_counts
  • 请包含输入数据帧(以及可以复制粘贴以实例化它的代码)和所需的输出数据帧。
  • 你的意思是不是 count()?
  • 这样做了@timgeb。关于如何解决它的任何想法?
  • 我看不到想要的输出df。

标签: python pandas loops count


【解决方案1】:

按照建议,使用 Series.value_counts 创建 count == 1 的国家/地区列表,并使用布尔索引和 Series.isin 进行过滤:

country_counts = df_path['country'].value_counts()
country_1 = country_counts[country_counts.eq(1)].index

df_path[df_path['country'].isin(country_1)]

[出]

    id  country
2   1   Indonesia
6   1   UK

【讨论】:

    猜你喜欢
    • 2018-07-17
    • 1970-01-01
    • 2022-08-16
    • 2018-04-04
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多