I want to pass only valid parameters to a function ("read_excel") I tried the following code but getting an error...
import pandas as pd
expected_keys=['io', 'sheet_name','header', 'names', 'index_col', 'usecols', 'squeeze', 'dtype', 'engine',
'converters', 'true_values', 'false_values', 'skiprows', 'nrows', 'na_values', 'parse_dates',
'date_parser', 'thousands', 'comment', 'skipfooter', 'convert_float']
def safe_read_excel(self, *args, **kwargs):
if set(kwargs.keys()).difference(set(expected_keys)):
raise ValueError('invalid parameter found')
return self.read_excel(f_name, *args, **kwargs)
pd.safe_read_excel = safe_read_excel
When I use the default "read_excel" method a dataframe is created...
df= pd.read_excel('sales_summary.xlsx', header=0)
But my custom method throws an error...
df= pd.safe_read_excel('sales_summary.xlsx', header=0)
AttributeError: 'str' object has no attribute 'read_excel'
How do I assign my function as pandas method?
That's because you are writing your safe_read_excel
function as a method of a class, while it is a "normal function" (or static method).
In practical words, you do not need self
:
def safe_read_excel(f_name, *args, **kwargs):
if set(kwargs.keys()).difference(set(expected_keys)):
raise ValueError('invalid parameter found')
return pd.read_excel(f_name, *args, **kwargs)
I changed the first input of the function from self
to f_name
and changed the return to pd.read_excel
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments