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

getting "TypeError: string indices must be integers error" while iterating dataframe in to a list

below is the data frame df

country           value
NETHERLANDS      230.156
UNITED STATES    60.128544
India            25.12 

getting issues while running the below code

data=[]
for i in df.iterrows():
    data.append({
       'c': i['country'],
       'v': i['value']
    })

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

>Solution :

iterrows yields both the row index and the row, so you need to catch both in the loop:

data=[]
for index, row in df.iterrows():  ## here
    data.append({'c': row['country'],
                 'v': row['value'],
                })

output:

[{'c': 'NETHERLANDS', 'v': 230.156},
 {'c': 'UNITED STATES', 'v': 60.128544},
 {'c': 'India', 'v': 25.12}]
pandas alternative

It would however be easier to run:

data = df.rename(columns={'country': 'c', 'value': 'v'}).to_dict('records')
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