The truth value of a Series is ambiguous - Error when calling a function
我知道下面的错误
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
很久以前就有人问过。
但是,我正在尝试创建一个基本函数,并用
1 2 3 4 5 6 | def hour_bus(df): if df[(df['hour'] >= '14:00:00') & (df['hour'] <= '23:00:00')&\ (df['week_day'] != 'Saturday') & (df['week_day'] != 'Sunday')]: return df['busy'] == 1 else: return df['busy'] == 0 |
我可以执行这个函数,但是当我使用数据帧调用它时,我会得到上面提到的错误。我遵循下面的线程和另一个线程来创建这个函数。在我的
不管怎样,当我执行以下操作时,我得到了我想要的输出。
1 2 | df['busy'] = np.where((df['hour'] >= '14:00:00') & (df['hour'] <= '23:00:00') & \ (df['week_day'] != 'Saturday') & (df['week_day'] != 'Sunday'),'1','0') |
我在我的
这个
1 | (df['hour'] >= '14:00:00') & (df['hour'] <= '23:00:00')& (df['week_day'] != 'Saturday') & (df['week_day'] != 'Sunday') |
给出一个布尔数组,当你用它索引你的
只是为了说明我的意思:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import pandas as pd df = pd.DataFrame({'a': [1,2,3,4]}) mask = df['a'] > 2 print(mask) # 0 False # 1 False # 2 True # 3 True # Name: a, dtype: bool indexed_df = df[mask] print(indexed_df) # a # 2 3 # 3 4 |
然而,它仍然是一个
1 2 | bool(indexed_df) # ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). |
您可以使用您使用的
1 2 3 4 5 | def hour_bus(df): mask = (df['hour'] >= '14:00:00') & (df['hour'] <= '23:00:00')& (df['week_day'] != 'Saturday') & (df['week_day'] != 'Sunday') res = df['busy'] == 0 res[mask] = (df['busy'] == 1)[mask] # replace the values where the mask is True return res |
然而,