gpt4 book ai didi

python - 如何从 Pandas 数据框中检索列值并检查条件

转载 作者:行者123 更新时间:2023-11-30 22:34:28 26 4
gpt4 key购买 nike

Dataframe 列 Class 由 2 个值 0 和 1 组成。我想计算 Class 0 有多少行以及 Class 1 有多少行。我编写了这样的代码

genuine_count=0
fraud_count=0
if credit_card_df['Class'] == 1:
fraud_count +=1
else:
genuine_count +=1
print "Genuine transactions"+genuine_count
print "Fraud transactions"+fraud_count

我收到此错误

ValueError                                Traceback (most recent call last)
<ipython-input-12-2e8ec920b69d> in <module>()
1 genuine_count=0
2 fraud_count=0
----> 3 if credit_card_df['Class'] == 1:
4 fraud_count +=1
5 else:

C:\Users\JAYASHREE\Anaconda2\lib\site-packages\pandas\core\generic.pyc in __nonzero__(self)
890 raise ValueError("The truth value of a {0} is ambiguous. "
891 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
--> 892 .format(self.__class__.__name__))
893
894 __bool__ = __nonzero__

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

请帮我解决。谢谢

最佳答案

谢天谢地,pandas 已经为您编写了此内容:

credit_card_df['Class'].value_counts()

或者,如果您想以自己的格式打印:

genuine_count, fraud_count = credit_card_df['Class'].value_counts(sort=True)

print "Genuine transactions"+genuine_count
print "Fraud transactions"+fraud_count

关于python - 如何从 Pandas 数据框中检索列值并检查条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44837748/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com