CYBER WEEK - EXTRA SAVINGS EVENT
TRY A FREE LESSON

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

can anyone help why my code doesn’t work

My Code:

fig, ax = plt.subplots(figsize=(15,20))
m = Basemap(projection='merc', llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180, urcrnrlon=180)
m.drawcoastlines()

# Start writing your solution below this line
def create_great_circles(df):
    for index,row in df.iterrows():
        latitude= df["end_lat"] - df["start_lat"]
        longitude = df["end_lon"] - df["start_lon"]
        if  (latitude and longitude) < 180:
            df.drawgreatcircle(df["start_lon"],df["start_lat"],df["end_lon"] , df["end_lat"] )
            
dfw = geo_routes[geo_routes["source"] == "DFW"]
plt.show()
create_great_circles(dfw)```

What I expected to happen:


What actually happened: 

Output

ValueErrorTraceback (most recent call last)
in ()
13 dfw = geo_routes[geo_routes[“source”] == “DFW”]
14 plt.show()
—> 15 create_great_circles(dfw)

in create_great_circles(df)
8 latitude= df[“end_lat”] - df[“start_lat”]
9 longitude = df[“end_lon”] - df[“start_lon”]
—> 10 if (latitude and longitude) < 180:
11 df.drawgreatcircle(df[“start_lon”],df[“start_lat”],df[“end_lon”] , df[“end_lat”] )
12

/dataquest/system/env/python3/lib/python3.4/site-packages/pandas/core/generic.py in nonzero(self)
1119 raise ValueError("The truth value of a {0} is ambiguous. "
1120 “Use a.empty, a.bool(), a.item(), a.any() or a.all().”
-> 1121 .format(self.class.name))
1122
1123 bool = nonzero

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

Hi @hshf1992

The codes below are giving you a series. Add this code in your for loop to verify:
> print(type(latitude))
> <class 'pandas.core.series.Series'>

Then the if code block is comparing series with an integer value here:

You have already broken your dataframe as index and row using df.iterrows() method. To get the latitude and longitude for each row, instead of computing df[col1] - df[col2], you can calculate row[col1] - row[col2].

And if you are experimenting with df[col1] .... then use appropriate code to check if all elements of the series are less than 180.

Also, the instruction says to compare abs diff with 180, so you may need to add abs() method as well.

2 Likes

@hshf1992

Here is a way to do it using df:

fig, ax = plt.subplots(figsize=(15,20))
m = Basemap(projection='merc', llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180, urcrnrlon=180)
m.drawcoastlines()

def create_great_circles(df):
    def drawcircle(row):
        m.drawgreatcircle(
            row["start_lon"],
            row["start_lat"],
            row["end_lon"],
            row["end_lat"]
        )
        
        
    lat_filter = (abs(df["end_lat"] - df["start_lat"]) < 180)
    lon_filter = (abs(df["end_lon"] - df["start_lon"]) < 180)
    df = df[lat_filter & lon_filter]    
    df.apply(drawcircle, axis=1)
    

dfw = geo_routes[geo_routes["source"] == "DFW"]
create_great_circles(dfw)
plt.show()
2 Likes

Thanks a lot i solved it, because all for your help here is my solution so basically assign the column start_lon do the rest the same etc to variable like this and put abs in the conditions .
::
def create_great_circles(df):
for index, row in df.iterrows():
end_lat = row[‘end_lat’]
start_lat = row[‘start_lat’]
end_lon= row[‘end_lon’]
start_lon = row[‘start_lon’]

    if abs(end_lat - start_lat) < 180 and abs(end_lon - start_lon) < 180:
            m.drawgreatcircle(start_lon, start_lat, end_lon, end_lat)

dfw = geo_routes[geo_routes[‘source’] == “DFW”]
create_great_circles(dfw)
plt.show()

2 Likes

also is there a way to read the Error sometimes the error makes no sense to me, like in this example :
::
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). ::

Hey @Sahil

Thanks for the detailed answer and you marked my answer as solution :grin: Not Complaining :rofl: !

1 Like

hey @hshf1992

Congrats… You are officially a Pythoner from today! :stuck_out_tongue_closed_eyes:

If you look closely at your error stack (the red big mumbo-jumbo in the output section), it actually tells us where the issue is:

Let’s break the error stack:

ValueErrorTraceback (most recent call last)
<ipython-input-1-adf8e66e8449> in <module>()
     34 dfw = geo_routes[geo_routes["source"] == "DFW"]
     35 
---> 36 create_great_circles(dfw)
     37 plt.show()
     38 

<ipython-input-1-adf8e66e8449> in create_great_circles(df)
     29         longitude = df["end_lon"] - df["start_lon"]
     30 
---> 31         if  abs(latitude) < 180 and abs(longitude) < 180:
     32             df.drawgreatcircle(df["start_lon"],df["start_lat"],df["end_lon"] , df["end_lat"] )
     33 

/dataquest/system/env/python3/lib/python3.4/site-packages/pandas/core/generic.py in __nonzero__(self)
   1119         raise ValueError("The truth value of a {0} is ambiguous. "
   1120                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1121                          .format(self.__class__.__name__))
   1122 
   1123     __bool__ = __nonzero__

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

On line 36 you pass the dataframe “dfw” to the create_great_circles function. The function starts to work on the dataframe. Then at line 31, python can’t make sense of your code, because it can’t compare, the two series objects with an integer value just like that.

Now we come to lines 1119 - 1121, which is not from your code, rather the packages/modules we first import. The package is the in-built mechanism that checks, if the values being compared are even compatible or not.

Like red apple & red apple (pass - equal), red apple & green apple (fail - not equal), apple and eggplant (error - not even comparable!).

So when it finds that apple and eggplant it directs the workflow to raise an exception - That exception is here
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Don’t worry, if you still don’t get it. Even I don’t get it many a times :wink:

2 Likes

@Rucha, I provided the answer, but you provided the details! :laughing:

1 Like