adhg
adhg

Reputation: 10863

From dataFrame to list with TypeError: string indices must be integers

I would like to create a list that looks like this at the end:

[
    {'name': 'Chrome', 'y': 550},
    {'name': 'IE', 'y': 203},
]

my data frame is:

df = pd.DataFrame({"CATEGORY":["Chrome","IE","FireFox","Safari","Opera","QQ"],"Users":[550,203,25,305,15,132]})

and in order to acheive this I'm trying something like this:

list(map(lambda row: {'name': df[row['CATEGORY']], 'y': row['Users']}, df))

but the result I get is: TypeError: string indices must be integers

Can anyone point out (1) what am I doing wrong and (2) how to fix it?

Upvotes: 0

Views: 831

Answers (2)

harpan
harpan

Reputation: 8631

You need to use .apply() with axis=1 so as to access columns. As you go, you need to construct your dictionary.

list(df.apply(lambda x: {'name': x['CATEGORY'], 'y': x['Users']}, axis=1))

Output:

[{'name': 'Chrome', 'y': 550},
 {'name': 'IE', 'y': 203},
 {'name': 'FireFox', 'y': 25},
 {'name': 'Safari', 'y': 305},
 {'name': 'Opera', 'y': 15},
 {'name': 'QQ', 'y': 132}]

Thank fixes your approach. The ideal way however, would be to use to_dict() as below:

df.rename(columns={'CATEGORY': 'name', 'Users': 'y'}).to_dict(orient='records')

Output:

[{'name': 'Chrome', 'y': 550},
 {'name': 'IE', 'y': 203},
 {'name': 'FireFox', 'y': 25},
 {'name': 'Safari', 'y': 305},
 {'name': 'Opera', 'y': 15},
 {'name': 'QQ', 'y': 132}]

This way your original df would be unaffected as well.

Upvotes: 1

akilat90
akilat90

Reputation: 5696

You can use:

df.columns = ['name', 'y'] # change the column names to the ones that you want
df.to_dict('records') # this returns a list of dictionaries for each row

[{'name': 'Chrome', 'y': 550},
{'name': 'IE', 'y': 203},
 {'name': 'FireFox', 'y': 25},
 {'name': 'Safari', 'y': 305},
 {'name': 'Opera', 'y': 15},
 {'name': 'QQ', 'y': 132}]

Upvotes: 1

Related Questions