简体   繁体   中英

What does the error “list indices must be integers or slices, not str” mean and how can I fix it?

I'm reading some data from Excel using Pandas in Python, this is how I read the data:

data_frame = pd.read_excel(file_location, usecols=catcode_column)
data_frame2 = pd.read_excel(file_location, usecols=smpl_column)

where the file_location is a string of the path and the usecols is simply the column that I want to read from the Excel file. Then I have 2 for loops, the first is is to just use the first 5 characters on the given column and the second uses the entire string:

    for i in data_frame:
        data_frame["catcode_column"] = data_frame[catcode_column_name].apply(lambda x: str(x)[:5])
    for j in data_frame2:
        data_frame2["smpl_column"] = data_frame2[smpl_column_name].apply(lambda y: y[:])

Now, I convert those data frames into lists using the following:

catcode_array = data_frame["catcode_column"].values.tolist()
smpl_array = data_frame2["smpl_column"].values.tolist()

and the the output when printing the catcode_array and smpl_array give me is the following:

Catcode Array: ['34123', '42253', '63334']

SMPL Array: ['Apartment-Midrise', 'Apartment-Midrise', 'Apartment-Midrise']

Now, I have a new array initialized to None with a size of 10000 and a counter initialized to 0. I iterate through the smpl_array , which is printed above, and if the index i of smpl_array is equal to the building_type_array index 0, then I want to store the value of the catcode_array at index i in the apartment_midrise at counter1 which at the beginning will be 0 so at the first index of that array and then increment the counter. It is worth nothing that building_type_array is an array of strings.

apartment_midrise = [None] * 10000

counter1 = 0

for i in smpl_array:
    if smpl_array[i] == building_type_array[0]:
        apartment_midrise[counter1] = catcode_array[i]
        counter1 += 1

But, I'm getting the following error in the if statement above:

if smpl_array[i] == building_type_array[0]:

TypeError: list indices must be integers or slices, not str

I've been trying to fix this without any luck. I would appreciate any help. Thanks!

In order to loop over a list and get the item and it's index in each iteration, you can use enumerate :

for i, smpl in enumerate(smpl_array):
    if smpl == building_type_array[0]:
        apartment_midrise[counter1] = catcode_array[i]
        counter1 += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM