soft-matter / trackpy

Python particle tracking toolkit
http://soft-matter.github.io/trackpy
Other
437 stars 131 forks source link

Error in trackpy.emsd() function: TypeError: mean() got an unexpected keyword argument 'level' #757

Closed Jelle111 closed 1 month ago

Jelle111 commented 4 months ago

I encountered an error while using the trackpy.emsd() function in the trackpy library. When calling trackpy.emsd() with my trajectory data;

em = tp.emsd(tm, 100/117., 20)

I received the following error:

TypeError: mean() got an unexpected keyword argument 'level'

Steps to Reproduce:

Execute the walkthrough tutorial with own Tif file Call the trackpy.emsd() function with the trajectory data. Expected Behavior: I expected the trackpy.emsd() function to compute the ensemble mean squared displacement (EMSD) without encountering any errors.

Actual Behavior: Instead, I received a TypeError indicating that the mean() function received an unexpected keyword argument 'level'.

Additional Information:

Version of trackpy library: 0.6.2 Operating System: MacOS Sonoma 14.2.1 with Apple M2 chip Python version: 3.11.5

b-grimaud commented 4 months ago

Can you post the full trace ? Which version of pandas are you using ?

xyc2718 commented 4 months ago

Due to changes in pandas version 2.0 and later, df.sum(level=1) is replaced by df.groupby(level=1).sum(), causing the emsd() function to be unavailable. I hope the author can update it as soon as possible.

Jelle111 commented 3 months ago

Can you post the full trace ? Which version of pandas are you using ?

Full trace:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[65], line 2
      1 #error: mean() got an unexpected keyword argument 'level'
----> 2 em = tp.emsd(tm, 100/117., 20)

File /Applications/anaconda3/lib/python3.11/site-packages/trackpy/motion.py:235, in emsd(traj, mpp, fps, max_lagtime, detail, pos_columns)
    233     ids.append(pid)
    234 msds = pandas_concat(msds, keys=ids, names=['particle', 'frame'])
--> 235 results = msds.mul(msds['N'], axis=0).mean(level=1)  # weighted average
    236 results = results.div(msds['N'].mean(level=1), axis=0)  # weights normalized
    237 # Above, lagt is lumped in with the rest for simplicity and speed.
    238 # Here, rebuild it from the frame index.

File /Applications/anaconda3/lib/python3.11/site-packages/pandas/core/frame.py:11335, in DataFrame.mean(self, axis, skipna, numeric_only, **kwargs)
  11327 @doc(make_doc("mean", ndim=2))
  11328 def mean(
  11329     self,
   (...)
  11333     **kwargs,
  11334 ):
> 11335     result = super().mean(axis, skipna, numeric_only, **kwargs)
  11336     if isinstance(result, Series):
  11337         result = result.__finalize__(self, method="mean")

File /Applications/anaconda3/lib/python3.11/site-packages/pandas/core/generic.py:11992, in NDFrame.mean(self, axis, skipna, numeric_only, **kwargs)
  11985 def mean(
  11986     self,
  11987     axis: Axis | None = 0,
   (...)
  11990     **kwargs,
  11991 ) -> Series | float:
> 11992     return self._stat_function(
  11993         "mean", nanops.nanmean, axis, skipna, numeric_only, **kwargs
  11994     )

File /Applications/anaconda3/lib/python3.11/site-packages/pandas/core/generic.py:11945, in NDFrame._stat_function(self, name, func, axis, skipna, numeric_only, **kwargs)
  11934 @final
  11935 def _stat_function(
  11936     self,
   (...)
  11942     **kwargs,
  11943 ):
  11944     assert name in ["median", "mean", "min", "max", "kurt", "skew"], name
> 11945     nv.validate_func(name, (), kwargs)
  11947     validate_bool_kwarg(skipna, "skipna", none_allowed=False)
  11949     return self._reduce(
  11950         func, name=name, axis=axis, skipna=skipna, numeric_only=numeric_only
  11951     )

File /Applications/anaconda3/lib/python3.11/site-packages/pandas/compat/numpy/function.py:416, in validate_func(fname, args, kwargs)
    413     return validate_stat_func(args, kwargs, fname=fname)
    415 validation_func = _validation_funcs[fname]
--> 416 return validation_func(args, kwargs)

File /Applications/anaconda3/lib/python3.11/site-packages/pandas/compat/numpy/function.py:88, in CompatValidator.__call__(self, args, kwargs, fname, max_fname_arg_count, method)
     86     validate_kwargs(fname, kwargs, self.defaults)
     87 elif method == "both":
---> 88     validate_args_and_kwargs(
     89         fname, args, kwargs, max_fname_arg_count, self.defaults
     90     )
     91 else:
     92     raise ValueError(f"invalid validation method '{method}'")

File /Applications/anaconda3/lib/python3.11/site-packages/pandas/util/_validators.py:223, in validate_args_and_kwargs(fname, args, kwargs, max_fname_arg_count, compat_args)
    218         raise TypeError(
    219             f"{fname}() got multiple values for keyword argument '{key}'"
    220         )
    222 kwargs.update(args_dict)
--> 223 validate_kwargs(fname, kwargs, compat_args)

File /Applications/anaconda3/lib/python3.11/site-packages/pandas/util/_validators.py:164, in validate_kwargs(fname, kwargs, compat_args)
    142 """
    143 Checks whether parameters passed to the **kwargs argument in a
    144 function `fname` are valid parameters as specified in `*compat_args`
   (...)
    161 map to the default values specified in `compat_args`
    162 """
    163 kwds = kwargs.copy()
--> 164 _check_for_invalid_keys(fname, kwargs, compat_args)
    165 _check_for_default_values(fname, kwds, compat_args)

File /Applications/anaconda3/lib/python3.11/site-packages/pandas/util/_validators.py:138, in _check_for_invalid_keys(fname, kwargs, compat_args)
    136 if diff:
    137     bad_arg = next(iter(diff))
--> 138     raise TypeError(f"{fname}() got an unexpected keyword argument '{bad_arg}'")

TypeError: mean() got an unexpected keyword argument 'level'

Pandas version: 2.1.4

hz-xiaxz commented 1 month ago

Just found this issue is duplicated with #750

nkeim commented 1 month ago

Closed for good (hopefully) by #758