Question: My Problems: Problem 1 : My problem is , If I convert Origin and Destination as numeric all the values become NaN and I am

My Problems:
Problem1:
My problem is, If I convert Origin and Destination as numeric all the values become NaN and I am getting error as below:
IndexError Traceback (most recent call last)
Cell In[186], line 124
122 for route in recommended_routes.itertuples(index=False):
123 origin, dest = route
-->124 revenue = revenue_per_route[(revenue_per_route['ORIGIN']== origin) & (revenue_per_route['DESTINATION']== dest)]['TotalRevenue'].values[0]
125 cost = cost_per_route[(revenue_per_route['ORIGIN']== origin) & (revenue_per_route['DESTINATION']== dest)]
126 breakeven_point = upfront_airplane_cost /(revenue - cost) if revenue > cost else float('inf')
IndexError: index 0 is out of bounds for axis 0 with size 0
Problem 2:
But if I dont convert them into Numeric then I am getting the Error as
TypeError Traceback (most recent call last)
Cell In[188], line 102
99return total_cost * num_round_trips
101 # Apply cost calculation and compute profitability
-->102 cost_per_route = revenue_per_route.apply(
103lambda x: calculate_route_cost((x['ORIGIN'], x['DESTINATION'])) if not pd.isna(x['ORIGIN']) and not pd.isna(x['DESTINATION']) else 0,
104 axis=1
105)
106 profit_per_route = revenue_per_route['TotalRevenue']- cost_per_route
108 top_10_profitable_routes = pd.DataFrame({
109'Origin': top_10_busiest_routes['ORIGIN'],
110'Dest': top_10_busiest_routes['DESTINATION'],
(...)
113'Profit': profit_per_route
114}).nlargest(10, 'Profit')
File /Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/pandas/core/frame.py:10374, in DataFrame.apply(self, func, axis, raw, result_type, args, by_row, engine, engine_kwargs, **kwargs)
10360 from pandas.core.apply import frame_apply
10362 op = frame_apply(
10363self,
10364 func=func,
(...)
10372 kwargs=kwargs,
10373)
...
51 def _sum(a, axis=None, dtype=None, out=None, keepdims=False,
52 initial=_NoValue, where=True):
--->53return umr_sum(a, axis, dtype, out, keepdims, initial, where)
TypeError: unsupported operand type(s) for +: 'float' and 'str'
----------------------------------------------
I thought of using anther column Distance from flights csv file which gives the Distance between Origin and Destination Airports in Miles but that has some data issues which I couldnt fix all of them
By default it is dtype=object ,I couldnt convert it to numeric when I tried I got following errors
Error 1Couldnt convert string Hundred to numeric.I fixed it by replacing it with number 100
Error 2Couldnt convert string Twenty to numeric. I fixed it by replacing it with number 20
Error 3-Couldnt convert string 2019-03-02 to numeric.
When I tried to convert to numeric getting below error:
TypeError Traceback (most recent call last)
Cell In[197], line 60
58 filtered_flights_df['DISTANCE'].fillna(0)
59 F1=filtered_flights_df.replace({'DISTANCE':{'Hundred':100, 'Twenty':20,'0H0u0n0d0r0e0d0':0,'':0,'2019-03-02':0,'****':0}})
--->60 F1.astype('Int')
62 #roundtrip_cost = filtered_flights_df.groupby(['ORIGIN', 'DESTINATION'])['DISTANCE'].sum().reset_index(name='Toipcost')
63 print (F1)
File /Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/pandas/core/generic.py:6643, in NDFrame.astype(self, dtype, copy, errors)
6637 results =[
6638 ser.astype(dtype, copy=copy, errors=errors) for _, ser in self.items()
6639]
6641 else:
6642# else, only a single dtype is given
->6643 new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors)
6644 res = self._constructor_from_mgr(new_data, axes=new_data.axes)
6645return res.__finalize__(self, method="astype")
File /Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/pandas/core/internals/managers.py:430, in BaseBlockManager.astype(self, dtype, copy, errors)
427 elif using_copy_on_write():
428 copy = False

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!