【问题标题】:Count occurrences of False or True in a column in pandas在 pandas 的列中计算 False 或 True 的出现次数
【发布时间】:2019-05-02 05:20:47
【问题描述】:

给定

patient_id  test_result has_cancer
0   79452   Negative    False
1   81667   Positive    True
2   76297   Negative    False
3   36593   Negative    False
4   53717   Negative    False
5   67134   Negative    False
6   40436   Negative    False

如何在python中计算一列中的False或True?

我一直在尝试:

# number of patients with cancer

number_of_patients_with_cancer= (df["has_cancer"]==True).count()
print(number_of_patients_with_cancer)

【问题讨论】:

标签: python pandas dataframe count


【解决方案1】:

所以你需要value_counts

df.col_name.value_counts()
Out[345]: 
False    6
True     1
Name: has_cancer, dtype: int64

【讨论】:

  • 谢谢!!如何只打印“False”? (我正在检查pandas.pydata.org/pandas-docs/stable/generated/… 但不是很清楚)
  • +1@NeyJTorres 作为记录,您可以通过附加.loc[False] 获得False 号码,如df.has_cancer.value_counts().loc[False]。但是,当您只需要 其中一个 TrueFalse(但不是两者)时,我认为使用像 (~df.has_cancer).sum() 这样的 Coldspeed 方法会更容易。
【解决方案2】:

如果 has_cancer 有 NaN:

false_count = (~df.has_cancer).sum()

如果has_cancer 没有 NaN,您可以通过不必事先否定掩码进行优化。

false_count = len(df) - df.has_cancer.sum()

同样,如果你想要 只是 True 值的计数,那就是

true_count = df.has_cancer.sum()

如果你想要两个,那就是

fc, tc = df.has_cancer.value_counts().sort_index().tolist()

【讨论】:

    【解决方案3】:
    0     True
    1    False
    2    False
    3    False
    4    False
    5    False
    6    False
    7    False
    8    False
    9    False
    

    如果上面的熊猫系列叫做例子

    example.sum()
    

    然后此代码输出 1,因为系列中只有一个 True 值。获取False的计数

    len(example) - example.sum()
    

    【讨论】:

      【解决方案4】:
      number_of_patients_with_cancer = df.has_cancer[df.has_cancer==True].count()
      

      【讨论】:

        【解决方案5】:

        只需将列相加即可得到 True 的计数。 False 只是 0 的特例,True 是 1 的特例。 False 计数将是您的行数减去该数。除非你有na's 在那里。

        【讨论】:

        • 如果我里面有 NaN?
        • na 的总和好像是0,上次我检查过。
        【解决方案6】:

        将上述数据框视为 df

        True_Count = df[df.has_cancer == True]
        
        len(True_Count)
        

        【讨论】:

          猜你喜欢
          • 2023-02-08
          • 2021-12-25
          • 1970-01-01
          • 2016-06-02
          • 2019-06-10
          • 1970-01-01
          • 1970-01-01
          • 2012-08-20
          • 1970-01-01
          相关资源
          最近更新 更多