What am I doing wrong? I am very new to python

I am trying to run this

final_df = pd.DataFrame() #empty dataframe

for csv_file in file_list:
    df = pd.read_csv(csv_file)
    csv_file_name = csv_file.split('\\')[7]
    print('Processing File : {}'.format(csv_file_name))
    df.columns = df.columns.str.replace(' ', '')
    df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'])
    df.set_index(['TIMESTAMP'], inplace=True)

    if 'Unnamed:13' in df.columns:
        df.drop(['Unnamed:13'], axis=1, inplace=True)

    df_trim = df.apply(lambda x: x.str.strip() if x.dtype == 'object' else x)

    new_df = df_trim[df_trim['SERIES'].isin(['EQ', 'BE', 'SM'])]
    final_df = final_df.append(new_df)

final_df.sort_index(inplace=True) #to sort by dates


Getting error

IndexError                                Traceback (most recent call last)
Cell In[17], line 5
      3 for csv_file in file_list:
      4     df = pd.read_csv(csv_file)
----> 5     csv_file_name = csv_file.split('\\')[7]
      6     print('Processing File : {}'.format(csv_file_name))
      7     df.columns = df.columns.str.replace(' ', '')

IndexError: list index out of range

What am I doing worng? what does this error mean?

>Solution :

It seems that when you split the string into array, you want to get element out of array range. So, the solution can be (if you want to extract last item):

csv_file_name = csv_file.split('\\')[len(csv_file.split('\\'))-1]

Leave a Reply