Python 为什么if语句迭代返回不明确的序列bool?

Python 为什么if语句迭代返回不明确的序列bool?,python,pandas,if-statement,iteration,valueerror,Python,Pandas,If Statement,Iteration,Valueerror,我对python还是个新手。我尝试使用带有2个条件的“if”语句遍历列表列。我一直得到的返回语句是序列的真值,当使用if语句迭代序列时,它是不明确的 下面是我的代码。数据框由来自Google Play Store的应用程序数据组成 import pandas as pd df = pd.read_csv("googleplaystore.csv") df.tail() df["Rating"].fillna(value = '0.0', inplace= True) medical_app_

我对python还是个新手。我尝试使用带有2个条件的“if”语句遍历列表列。我一直得到的返回语句是序列的真值,当使用if语句迭代序列时,它是不明确的

下面是我的代码。数据框由来自Google Play Store的应用程序数据组成

import pandas as pd
df = pd.read_csv("googleplaystore.csv")
df.tail()

df["Rating"].fillna(value = '0.0', inplace= True)

medical_app_ratings = []

for row in df[1:]:
    rating = df.Rating
    genre = df.Genres
    if genre == "Medical":
        medical_app_ratings.append(rating)

ValueError                                Traceback (most recent call last)
<ipython-input-154-51c7806c01da> in <module>
      5     rating = df.Rating
      6     genre = df.Genres
----> 7     if genre == "Medical":
      8         medical_app_ratings.append(rating).bool()
      9 

~\anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
   1477     def __nonzero__(self):
   1478         raise ValueError(
-> 1479             f"The truth value of a {type(self).__name__} is ambiguous. "
   1480             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1481         )

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


如果有人能告诉我我做错了什么,我将不胜感激

我假设您希望遍历数据帧,我建议使用df.iterrows来完成它

下面是一个关于如何使用它的示例:

medical_app_ratings = []
for i, row in df.iterrows():
  rating = row.Rating
  genre = row.Genres
  if genre == "Medical":
    medical_app_ratings.append(rating)
您需要:df.loc[df['Genres']=='Medical','Rating']。在使用数据帧时,尝试摆脱迭代的想法,使用pandas和numpy提供的矢量化方法。