我试图通过对现有列执行一些操作来创建新列,但这在代码中引发了一个键错误.我try 通过使用df.Columns和Copy粘贴完全相同的名称来对其进行调试,但仍然收到相同的错误.我的代码如下:
def calculate_elasticity(group):
sales_change = group['Primary Sales Quantity'].pct_change()
price_change = group['MRP'].pct_change()
elasticity = sales_change / price_change
return elasticity
df['Variant-based Elasticity'] = df.groupby('Variant').transform(calculate_elasticity)
显示的错误是
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3801 try:
-> 3802 return self._engine.get_loc(casted_key)
3803 except KeyError as err:
16 frames
pandas/_libs/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()
KeyError: 'Primary Sales Quantity'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3802 return self._engine.get_loc(casted_key)
3803 except KeyError as err:
-> 3804 raise KeyError(key) from err
3805 except TypeError:
3806 # If we have a listlike key, _check_indexing_error will raise
KeyError: 'Primary Sales Quantity'
我try 进行调试,下面是df.Columns的结果
Index(['Cal. year / month', 'Material', 'Product Name', 'MRP', 'Distribution Channel (Master)', 'Unnamed: 5', 'L1 Prod Category', 'L2 Prod Brand', 'L3 Prod Sub-Category', 'State', 'Primary Actual GSV Value', 'Primary Sales Qty (CS)', 'Secondary GSV', 'Secondary sales Qty(CS)', 'Primary Volume(MT/KL)', 'Secondary Volume(MT/KL)', 'Variant', 'Weight', 'Offers', 'Primary Sales Quantity'], dtype='object')
个
并且结果为print(df['Primary Sales Quantity'])
是
0 155
1 16953
2 455
3 138
4 2653
...
14147 6
14148 1
14149 8428
14150 237
14151 24
Name: Primary Sales Quantity, Length: 14152, dtype: int64
我try 使用列名进行调试.我甚至可以使用该名称访问该列,只是在此函数中抛出了错误.