如何从Pandas数据帧中检索列值并检查条件

时间:2017-06-30 02:35:33

标签: python pandas dataframe

Dataframe column Class由2个值0和1组成.I想要计算Class 0的行数和Class 1的行数.I编写这样的代码

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().

请帮我解决。谢谢

2 个答案:

答案 0 :(得分:2)

谢天谢地,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

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

windows_zipfile

答案 1 :(得分:1)

只是做:

pandas

我希望这会有所帮助。