[SOLVED] Pandas apply getting KeyError:


I was looking at this answer by Roman Pekar for using apply. I initially copied the code exactly and it worked fine. Then I used it on my df3 that is created from a csv file and I got a KeyError. I checked datatypes the columns I was using are int64, so that is okay. I don’t have nulls. If I can get this working then I will make the function more complex. How do I get this working?

def fxy(x, y):
    return x * y

df3 = pd.read_csv(path + 'test_data.csv', usecols=[0,1,2])
df3['Area'] = df3.apply(lambda x: fxy(x['Len'], x['Width']))

Trace back

Traceback (most recent call last):
File "f:\...\my_file.py", line 54, in <module>
df3['Area'] = df3.apply(lambda x: fxy(x['Len'], x['Width']))
File "C:\...\frame.py", line 8833, in apply
return op.apply().__finalize__(self, method="apply")
File "C:\...\apply.py", line 727, in apply
return self.apply_standard()
File "C:\...\apply.py", line 851, in apply_standard
results, res_index = self.apply_series_generator()
File "C:\...\apply.py", line 867, in apply_series_generator
results[i] = self.f(v)
File "f:\...\my_file.py", line 54, in <lambda>
df3['Area'] = df3.apply(lambda x: fxy(x['Len'], x['Width']))
File "C:\...\series.py", line 958, in __getitem__
return self._get_value(key)
File "C:\...\series.py", line 1069, in _get_value
loc = self.index.get_loc(label)
File "C:\...\range.py", line 389, in get_loc
raise KeyError(key)
KeyError: 'Len'

I don’t see a way to attach the csv file. Below is Sample df3 if I save the below with excel as "CSV (Comma delimited)(*.csv) I get the same results.

ID Len Width
A 170 4
B 362 5
C 12 15
D 42 7
E 15 3
F 46 49
G 71 74


I think you miss the axis=1 on apply:

df3['Area'] = df3.apply(lambda x: fxy(x['Len'], x['Width']), axis=1)

But in your case, you can just do:

df3['Area'] = df3['Len'] * df3['Width']

# Output
   ID  Len  Width  Area
0  A   170      4   680
1  B   362      5  1810
2  C    12     15   180
3  D    42      7   294
4  E    15      3    45
5  F    46     49  2254
6  G    71     74  5254

Answered By – Corralien

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.