Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass my variable as a string into function

I have wrote lines of code to convert items of a pandas dataframe column to a dict with appropriate values. The code looks like this:

states = df.STATE.unique()
states.sort()
states_values = [i for i in range(0,len(states))]
state_dict = {states[i]: states_values[i] for i in range(len(states))}

But I have many columns to convert so I tried using a function and wrote a function like this

def make_dict(dataframe,column_name):
    keys = dataframe.column_name.unique()
    keys.sort()
    values = [i for i in range(0,len(keys))]
    dict = {keys[i]: values[i] for i in range(len(keys))}
    return dict

But When I tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

city_dict = make_dict(df,'CITY')

Where CITY is my column name, it throws an error

AttributeError: 'DataFrame' object has no attribute 'column_name'

I have tried setting a variable and did it but same error.

tried with df['CITY'] over df.CITY but still doesn’t work out.
Please let me know what am I missing.

>Solution :

You can use getattr() to fetch arbitrary attributes.

keys = getattr(dataframe, column_name).unique()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading