Reputation: 81
I have a DataFrame that sometimes has a row called (UnSpecified) and sometimes don't. When I try to drop the row by the name and it doesn't exist I get a "(UnSpecified) not found in axis" error.
### sales 2018 ###
sales_2018 = pd.read_csv('sales 2018.csv')
# gross sales
gross_sales_2018_pivot = pd.DataFrame(pd.pivot_table(sales_2018, values=['GROSS SALES'], index=['DAYPARTNAME'], columns=['DAY OF WEEK'], aggfunc=np.sum))
gross_sales_2018_pivot = gross_sales_2018_pivot.drop('(UnSpecified)', axis=0)
gross_sales_2018_pivot.to_excel(writer, sheet_name='overall')
writer.save()
How can I create a loop to make it ignore/pass the error if there is no (UnSpecified) row?
Upvotes: 3
Views: 3512
Reputation: 2119
gross_sales_2018_pivot = gross_sales_2018_pivot.loc[condition for not unspecified, :]
Example:
gross_sales_2018_pivot = gross_sales_2018_pivot.loc[gross_sales_2018_pivot['important_col'] != 'trash', :]
Upvotes: 0
Reputation: 101
From the documentation:
gross_sales_2018_pivot = gross_sales_2018_pivot.drop('(UnSpecified)', axis=0, errors='ignore')
Upvotes: 3