'KeyError "[.....]" not in index
I am working on a project for work and was handed this code after having no previous experience with Python. I'm getting a KeyError message, and the line above that has some red text that I am also unsure about. Here's the exact text:
File "/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py", line 1327, in _convert_to_indexer
.format(mask=objarr[mask]))
KeyError: "['First name' 'Last name' 'Company' 'Email address - other' 'Opened At'\n 'Company.1'] not in index"
I have been looking into tutorials all day and understand that this is an issue with the fact that this DataFrame doesn't have an index, but I think that is due to the fact that it is importing data from a file that doesn't have a set name.
Here's the beginning portion of the code that I believe has the issue:
import pandas as pd
import numpy as np
import glob, os
import re
# In[21]:
db = pd.DataFrame()
for file in glob.glob("report_*.csv"):
df = pd.read_csv(file, encoding = "ISO-8859-1")
db = db.append(df,ignore_index=True)
# In[22]:
db= db[['First name','Last name', 'Company', 'Email address - other','Opened At','Company.1']]
# In[23]:
db.columns = [c.replace(' ', '_') for c in db.columns]
db.columns = [c.replace('-', '_') for c in db.columns]
db.columns = [c.replace('.', '_') for c in db.columns]
When I print(bd) I get this:
Empty DataFrame
Columns: []
Index: []
So I recognize that I need to add an Index but I'm not sure what it should be. The resulting file should have 6 columns, I believe, but the number of rows varies.
I am willing to provide whatever information is necessary I'm just at a loss of what to do and would appreciate any help at all!
Edit: Print(df.head()) yields:
print(df.head())
Traceback (most recent call last):
File "<ipython-input-17-873aa293d964>", line 1, in <module>
print(df.head())
NameError: name 'df' is not defined
Solution 1:[1]
All the COLUMN are having a space "Opened At", we have an extra space in "Opened At". We need to get rid of it.
df= pd.read_csv(fileName)
df=df.rename({"Opened At":"Opened_At"},axis=1)
Hope this will solve your problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yumnam_jr Mangang |
