Skip to content

add .dt and .str accessors to DataArray (like pandas.Series) #358

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
shoyer opened this issue Mar 3, 2015 · 4 comments · Fixed by #1356
Closed

add .dt and .str accessors to DataArray (like pandas.Series) #358

shoyer opened this issue Mar 3, 2015 · 4 comments · Fixed by #1356

Comments

@shoyer
Copy link
Member

shoyer commented Mar 3, 2015

Something like this should work: observed.time.dt.to_pydatetime().

This could simply be wrappers of the pandas methods.

@darothen
Copy link

darothen commented Apr 3, 2017

Working on a project today which would greatly benefit from having the .dt accessors. Given that this issue is nearly two years old, any thoughts on what it would take to resolve in the present codebase? Still as straightforward as wrappers on the pandas time series methods?

@shoyer
Copy link
Member Author

shoyer commented Apr 3, 2017

Yes, I think this would be quite straightforward. I think the easiest way to do it would simply be to reuse xarray's accessor interface (i.e., register_dataarray_accessor) and then implement all the desired methods/properties.

@darothen
Copy link

darothen commented Apr 4, 2017

Proof of concept, borrowing liberally from pandas. I think this will be pretty straightforward to hook up into xarray. I wonder, is there any way to register such an accessor with DataArrays that have a specific dtype? Ideally we'd only want to expose this accessor if a DataArray was a numpy.datetime64 type under the hood.

@shoyer
Copy link
Member Author

shoyer commented Apr 4, 2017

Yes, looks pretty good. It would be nice to consolidate this with xarray's current logic for getting virtual datetime variables (they should probably delegate to the accessor):

def _get_virtual_variable(variables, key, level_vars=None, dim_sizes=None):

I wonder, is there any way to register such an accessor with DataArrays that have a specific dtype?

The simplest option is to raise AttributeError or TypeError in the constructor, e.g.,

@xarray.register_dataarray_accessor('float_only')
class FloatOnlyAccessor(object):
  def __init__(self, parent):
    if parent.dtype.kind != 'f':
      raise TypeError('wrong dtype')
    self.parent = parent
>>> xarray.DataArray(1.5).float_only
<__main__.FloatOnlyAccessor at 0x8d51350>
>>> xarray.DataArray(1).float_only
TypeError: wrong dtype

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants