Home > Software engineering >  TypeError: unhashable type: 'list' df_data = df[columns]
TypeError: unhashable type: 'list' df_data = df[columns]

Time:01-15

I'm trying to import multiple sheets from excel file but it giving me " unhashable type: 'list' " error.

df = pd.read_excel('example.xlsx', sheet_name=None)

columns = ['SR_NO', 'NTN', 'NAME']
df_data = df[columns]
records = df_data.values.tolist()

NOTE: For the single sheet its working fine

CodePudding user response:

If use sheet_name=None then get dictionary of DataFrames for each sheetname with keys by sheetname texts.

So if need specify sheet_name use:

df = pd.read_excel('example.xlsx', sheet_name='my_sheet')

Or for first:

df = pd.read_excel('example.xlsx')

If need processing all sheetnames converted to DataFrames:

dfs = pd.read_excel('example.xlsx', sheet_name=None)

#for test sheetnames
print (dfs.keys())

d = {}
for k, v in dfs.items():
    columns = ['SR_NO', 'NTN', 'NAME']
    df_data = v[columns]
    records = df_data.values.tolist()
    d[k] = records

#for test sheetnames
print (d.keys())

print (d['my_sheet'])

d = {k: v[['SR_NO', 'NTN', 'NAME']].values.tolist() 
        for k, v in  pd.read_excel('example.xlsx', sheet_name=None).items()}

CodePudding user response:

Muhammad Osama, welcome to stack overflow.

I don't fully understand what you are trying to achieve, but from my understanding, see if this snippet of code will help:

import pandas as pd

my_sheet_list = ['Worksheet']

for sheet in my_sheet_list:
    df = pd.read_excel('test.xlsx', sheet_name=sheet)
    line_count = 0
    for row in df:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count  = 1
        else:
            print(f'row 1: {row[1]}')
            line_count  = 1
    print(f'Processed {line_count} lines.')

This will loop over all sheet names in an Excel file, you will have to manually input the sheet names in my_sheet_list. It will first print the columns (headers) and then it will continue and you can grab any information that you need based on the column numbers in the row.

Is this helping you ?

  •  Tags:  
  • Related