9

I have a pandas dataframe like below :

   profile_index  point_index         z              x             y
0              0            1 -0.885429  297903.323027  6.669492e+06
1              0            2 -0.820151  297904.117752  6.669492e+06
2              0            3 -0.729671  297904.912476  6.669491e+06
3              0            4 -0.649332  297905.707201  6.669490e+06
4              1            1 -0.692186  297906.501926  6.669490e+06
5              1            2 -0.885429  297903.323027  6.669492e+06
6              1            3 -0.820151  297904.117752  6.669492e+06
3              1            4 -0.649332  297905.707201  6.669490e+06

I want to create a new "z_gauss" column by applying a convolution (numpy.convolve) with a gaussian filter on vectors (column z) corresponding to a group of rows in my dataframe with the same "profile_index".

I've tried to do something like

data["z_gauss"] = data.groupby('profile_index').apply(lambda x: np.convolve(x, gaussian, 'same'))

where gaussian is my gaussian filter (vector). But I get some errors like ValueError: object too deep for desired array

Do you have any advices/hints on how to proceed ? Should I split my dataframe into different ones ?

2
  • 1
    data.groupby('profile_index')['x'].apply(lambda x: np.convolve(x, gaussian, 'same'))? Dec 3, 2019 at 17:12
  • Thx, this looks like quite an improvement, but it returns a vector per row that has the size of the group whereas i need a single value per row. Any way to transpose back the vectors along the rows ?
    – Beinje
    Dec 3, 2019 at 17:34

1 Answer 1

1

You want to use a transform instead of an apply. This will avoid inserting a vector wth the size of the group per row:

data["z_gauss"] = (data.groupby('profile_index')['z']
                   .transform(lambda x: np.convolve(x, gaussian, 'same')))
3
  • 1
    Indeed, I changed the method from apply to transform and I get what I expected, thank you ! I need to read more documention about the difference between the two methods though because I don't really understand this behaviour. Btw, you should update your code snippet because it still mention the apply method.
    – Beinje
    Dec 4, 2019 at 13:24
  • No prob. Updated :)
    – Brandon
    Dec 4, 2019 at 16:37
  • I don't know if this is the right place to ask (maybe I should start a new thread), but : is it possible to apply this transformation on a slice (because my filter doesn't apply on boundaries) of the Series, or should I change values back once the transformation is done ?
    – Beinje
    Dec 9, 2019 at 13:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.