Search code examples
python-3.xpandastime-serieskeyerror

I'm getting a Key Error Message after using a For loop and then trying to access the columns by name in a Python Series




I hope that someone can help me here. I'm pretty new to Python and I got stuck with a For Loop to create a couple of time shifts for my datetime Series. Once I iterated over the shifts and want access the columns by name to calculate the percentage change, I get a Key Error.

Here is what my code looks like:

i=1
x=50
for i in range (x):
    df_data_1['visits_lag_',i] = df_data_1['visits'].shift(i)

The output looks the following: df.dtypes

Now, If I want to calculate or access one of the newly created columns, I receive a Key Error Message:

 df_data_1['percent_change_test'] = 
(df_data_1['visits']/df_data_1['(visits_lag_, 1)'])*100

It says:

Key Error

Please, can anyone help me here, what I'm doing all wrong.


Solution

  • I think the problem is related to how you call the newly created column. Instead of:

    df_data_1["(visits_lag_, 1)"]
    

    Try to do:

    df_data_1[("visits_lag_", 1)]