Skip to main content
 首页 » 编程设计

python之使用 if else 语句的输出创建新列会导致错误

2025年05月04日8JeffreyZhao

我正在使用下面的代码,

if(df.month == 3 or df.month == 4 or df.month == 5): 
    df.test = 'A' 
elif(df.month == 6 or df.month == 7 or df.month == 8): 
    df.test = 'B' 
else: 
    df.test = 'C' 

但是在使用这个的时候,我得到了以下错误,

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

更新:

print df.columns 
 
Unnamed: 0      int64 
year            int64 
month           int64 
day             int64 
dep_time      float64 
dep_delay     float64 
arr_time      float64 
arr_delay     float64 
carrier        object 
tailnum        object 
flight          int64 
origin         object 
dest           object 
air_time      float64 
distance        int64 
hour          float64 
minute        float64 
 
 
print df.dtypes 
 
dtype: object 

谁能帮我找出这里的错误?

请您参考如下方法:

我认为最好的是使用 loc和 isin ,因为您无法使用 if 或 elif 将标量与数组进行比较,因此它变得不明确:

print df 
 
   year  month  day 
0  2005      3   20 
1  2005      4   20 
2  2005      5   20 
3  2005      6   20 
4  2005      7   20 
5  2005      8   20 
6  2005      9   20 
 
df['test'] = 'C' 
df.loc[df['month'].isin([3,4,5]) , 'test'] = 'A' 
df.loc[df['month'].isin([6,7,8]) , 'test'] = 'B' 
 
print df   
 
   year  month  day test 
0  2005      3   20    A 
1  2005      4   20    A 
2  2005      5   20    A 
3  2005      6   20    B 
4  2005      7   20    B 
5  2005      8   20    B 
6  2005      9   20    C 

或者你可以用 C 这样的值填充 test 列:

df.loc[df['month'].isin([3,4,5]) , 'test'] = 'A' 
df.loc[df['month'].isin([6,7,8]) , 'test'] = 'B' 
df.loc[df['month'].isin([1,2,9,10,11,12]) , 'test'] = 'C' 
 
print df     
 
   year  month  day test 
0  2005      3   20    A 
1  2005      4   20    A 
2  2005      5   20    A 
3  2005      6   20    B 
4  2005      7   20    B 
5  2005      8   20    B 
6  2005      9   20    C