Home > Blockchain >  getting "TypeError: string indices must be integers error" while iterating dataframe in to
getting "TypeError: string indices must be integers error" while iterating dataframe in to

Time:02-05

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']
    })

CodePudding user response:

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')
  •  Tags:  
  • Related