0

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

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.

1 Answer 1

1

You can use getattr() to fetch arbitrary attributes.

keys = getattr(dataframe, column_name).unique()
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much @John, This solved everything. Thank you!!
Sorry for that I couldn't upvote your answer as my reputation is too low!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.