Error: string indices must be integers in loop

Asked

Viewed 60 times

0

good evening, I’m needing to do a for a request based on an excel, with that I’m doing so:

df1 = pd.read_excel('D:/repositorio/python/leitura.xls')
count = 0
for y in df1['EAN']:   
        data ="{\"productCode\":\"EAN%d\"}" % (y)

It works properly, but I need to use other Excel Po fields, and I’m trying to do so:

df1 = pd.read_excel('D:/repositorio/python/leitura.xls')
count = 0
for y in df1:   
        data ="{\"productCode\":\"EAN%d\"}" % (y['EAN'])

Only then this mistake is making:

TypeError                                 Traceback (most recent call last)
C:\Users\OTACIO~1.BAR\AppData\Local\Temp/ipykernel_11848/1268633844.py in <module>
     19 for y in df1:
     20 
---> 21         data ="{\"productCode\":\"EAN%d\"}" % (y['EAN'])
TypeError: string indices must be integers

Could you help me with the right way to do it?

1 answer

3


You should use the iterrows function of the panda dataframe.

Do something like:

for index, Row in df1.iterrows(): data ="{"productCode":"EAN%d"}" % (Row['EAN'])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.