0

I am getting KeyError: "Index(['scanCd'], dtype='object') not in index" error when trying to put the columns of 2 dataframes side by side after concatenating.

I am not able find out the root cause of the issue can someone help?

i had already read some of the questions posted but thosse solutions didnt seem to help. my main aim to compare 2 df's and highlight the differences

{Code:

val ={'lineNum':[10624,11192,15596,15790], 'scanCd':[10,20,30,40], 'brandName':['HP','Dell','Samsung','Lenovo']}
dft = pd.DataFrame(val, columns= ['lineNum','scanCd','brandName'])
dfm = dft.copy()
# change the values of few elements
dfm.loc[0, 'brandName'] = 'H-P'
dfm.loc[1, 'brandName'] = 'DELL'
dfm.loc[2, 'brandName'] = 'SAMSUNG'
df_all = pd.concat([dft.set_index('scanCd'), dfm.set_index('scanCd')], 
                   axis='columns', keys=['dft', 'dfm'])

df_final = df_all.swaplevel(axis='columns')[dft.columns[0:]]


Error:
Traceback (most recent call last):

  File "<ipython-input-318-16965db0a52e>", line 11, in <module>
    df_final = df_all.swaplevel(axis='columns')[dft.columns[0:]]

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2986, in __getitem__
    indexer = self.loc._convert_to_indexer(key, axis=1, raise_missing=True)

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1285, in _convert_to_indexer
    return self._get_listlike_indexer(obj, axis, **kwargs)[1]

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1075, in _get_listlike_indexer
    indexer, keyarr = ax._convert_listlike_indexer(key, kind=self.name)

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\multi.py", line 2408, in _convert_listlike_indexer
    raise KeyError("%s not in index" % keyarr[mask])

KeyError: "Index(['scanCd'], dtype='object') not in index"
}
Maharajaparaman
  • 141
  • 3
  • 12

0 Answers0