【问题标题】:Python/Pandas, .count not working on larger data framePython/Pandas,.count 不适用于更大的数据框
【发布时间】:2020-01-11 02:11:15
【问题描述】:

我正在尝试计算数据框中真/假值的数量,如下所示:

df = pd.DataFrame({'a': [True, False, True],
                  'b': [True, True, True],
                  'c': [False, False, True]})
count_cols = ['a', 'b', 'c']
df['count'] = df[df[count_cols] == True].count(axis=1)

这在这个例子中运行良好。但是当我在我的实际 df (shape - (25168, 303)) 上测试它时,我收到以下错误:

我从 - What does `ValueError: cannot reindex from a duplicate axis` mean? 了解到,这通常发生在索引中有重复值时,我已经尝试了 df.reindex()df[~df.index.duplicated()],但我仍然收到相同的错误消息。

【问题讨论】:

  • 你试过df.sum(axis=1)吗?
  • 谢谢,但这会引发同样的错误

标签: python pandas


【解决方案1】:

按列表过滤列并按 sum 计算 Trues 值 - Trues 的处理方式类似于 1s:

df['count'] = df[count_cols].sum(axis=1)
print (df)
       a     b      c  count
0   True  True  False      2
1  False  True  False      1
2   True  True   True      3

编辑:为避免错误,一种可能的解决方案是将值转换为 numpy 数组:

df['count'] = np.sum(df[count_cols].values, axis=1)
print (df)
       a     b      c  count
0   True  True  False      2
1  False  True  False      1
2   True  True   True      3

【讨论】:

  • 谢谢,但是df[count_cols].sum(axis=1) 会抛出同样的错误
  • 完美,谢谢!你知道为什么我的适用于测试 df 而不是大的吗?
  • @Maverick 似乎有些数据相关的问题,很难知道
猜你喜欢
  • 2018-06-15
  • 2017-10-29
  • 2014-12-15
  • 2017-04-01
  • 2020-05-21
  • 1970-01-01
  • 2015-11-21
  • 2012-11-08
  • 1970-01-01
相关资源
最近更新 更多