Skip to content
Advertisement

when using group_by: TypeError: incompatible index of inserted column with frame index

I have a df that I’ve read from sql:

JavaScript

I then try and get the average of the last 5 days and add it to a new column:

JavaScript

Which gives me the following error:

JavaScript

Any ideas what’s going wrong here? Previously this worked and now it’s throwing an error – and I can’t seem to figure out why

Advertisement

Answer

Chain Series.to_numpy to add the values as a np.array and make sure to add sort=False inside df.groupby:

JavaScript

Your initial approach fails, because the df.groupby method that you are using, returns a pd.Series with a different index than your df. E.g.:

JavaScript

So, it is saying it is unable to map this onto:

JavaScript

With a np.array you don’t have this problem. You could also have used:

JavaScript

In this case, you don’t need to add sort=False, as it will match correctly on the index values.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement