-1

I created a treeview to display the data imported from an excel file.

    def afficher():
        fichier = r"*.xlsx"
        df = pd.read_excel(fichier)
        for row in df:
            refOF = row['refOF']
            refP = row['refP']
            refC = row['refC']
            nbreP = row['nbreP']
            dateFF = row['dateFF']
            self.ordreF.insert("", 0, values=(refOF, refP, refC, nbreP, dateFF))

but I encounter the following error:

refOF = row['refOF']
TypeError: string indices must be integers

please tell me how I can solve this problem.

jottbe
  • 4,228
  • 1
  • 15
  • 31
Abdess
  • 3
  • 2
  • Have you tried printing out the "row" in `for row in df` to see what happened? Please also consider providing sample data in a [reproducible way](https://stackoverflow.com/questions/20109391). Otherwise people won't be able to test. – Bill Huang Nov 22 '20 at 00:17

2 Answers2

0

With your loop you are actually not iterating over the rows, but over the column names. That is the reason for the error message, because row is the string with the colum name and if you use [] you need to specify an integer or an integer based slice, but not a string. To make your code work, you would just need to modify your code a bit to iterate over the rows:

def afficher():
    fichier = r"*.xlsx"
    df = pd.read_excel(fichier)
    for idx, row in df.iterrows():
        refOF = row['refOF']
        refP = row['refP']
        refC = row['refC']
        nbreP = row['nbreP']
        dateFF = row['dateFF']
        self.ordreF.insert("", 0, values=(refOF, refP, refC, nbreP, dateFF))
jottbe
  • 4,228
  • 1
  • 15
  • 31
0

Another way is replacing the original for loop with the following:

for tup in df[['refOF', 'refP', 'refC', 'nbreP', 'dateFF']].itertuples(index=False, name=None):
    self.ordreF.insert("", 0, values=tup)

It works because df.itertuples(index=False, name=None) returns a regular tuple without index in the assigned column order. The tuple can be fed into the values= argument directly.

Bill Huang
  • 4,491
  • 2
  • 13
  • 31