且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python使用if函数:ValueError:Series的真实值不明确.使用a.empty,a.bool(),a.item(),a.any()或a.all()

更新时间:2021-12-18 18:08:38

您看到的异常是由于您尝试根据一组单一条件来评估具有许多不同条目的系列. 简要地,让我们看一下您的操作:

The exception you are seeing is due to the fact that you try to evaluate a series with many different entries against a set of single conditions. Briefly, let's have a look what you do:

错误分析(为什么不那样做):

首先,您确实获取了pandas数据框列,然后将其转换为日期时间,当然它也返回了列(系列).

time = pd.to_datetime(df.dttm_utc) # Convert content of dttm_utc COLUMN to datetime
                                   # This returns a dataframe COLUMN / series
Month = time.dt.month              # Convert content of your COLUMN/series to month
Day = time.dt.day                  # Convert content of your COLUMN/series to month
Hour = time.dt.Hour                # Convert content of your COLUMN/series to month

您的错误:然后尝试评估系列中的特定条件:

if (Month == whatever_condition): 
    do_something()

但是,您不能将单个条件与一系列条件进行比较,至少不能这样. Python不知道您指的是该系列中的哪个条目,因为其中的某些值可能与其他值不同.这意味着,对于该系列中的某些项目,条件可能会得到满足,而对于其他项目则不能.因此,ValueError: The truth value of a series is ambiguous.

However, you can't compare a single condition to a series, at least not like that. Python doesn't know which entry in the series you mean, as some values in it may be different to others. That means, for some items in the series the condition may be fulfilled, for others not. Hence the ValueError: The truth value of a series is ambiguous.

您要做什么:

逐项评估,理想情况下以矢量化方式进行.我的建议:始终保持在熊猫数据框中:

Evaluate item by item, ideally in a vectorized way. My suggestion: stay in the pandas dataframe all time:

df['Datetime'] = pd.to_datetime(df['dttm_utc']) # Add second column with datetime format
df['Month'] = df.Datetime.dt.month     # Extract month and add to new column
                                                # Same for day
df.loc[(df.Month < 3), 'InDayLightSavings'] = False 
# You can add multiple conditions here
# Finally, your filter:
df.loc[(df.InDayLightSavings == True), 'Time'] = df['Time'] - dt.timedelta(hours=1) 
# dt when import datetime as dt, else just datetime

进一步阅读此处此处在这里.