Wind Circulation
Wind Circulation

Reputation: 107

How to group the dataarray by day and night?

I have a dataarray of time (96) and level (27) coordinates. I want to group the array by day and night. The timezone is UTC. I should get two dataarrays, one which contains only days, e.g. day (06:00 to 18:00) and night (18:00 to 06:00).

There is a groupby function in xarray and pandas, but I don't think know if there are day and night attributes available there. How can it be done?

Below is my dataarray:

xarray.DataArray'r' time: 96 level: 27
96.67 99.58 98.07 93.94 89.31 78.26 ... 93.84 92.73 92.42 91.3 87.91
Coordinates:
time
(time)
datetime64[ns]
2021-05-14 ... 2021-05-17T23:00:00
level
(level)
float64
100.0 125.0 150.0 ... 975.0 1e+03
Attributes: (0)

Upvotes: 0

Views: 524

Answers (3)

DaveR
DaveR

Reputation: 2358

The logical steps (I can give you the code if I can reproduce your data) are:

  1. Contain a column base on time indicating if it is day or night.
  2. Do a groupby on that new column.

Some example code:

import pandas as pd


df = pd.DataFrame({'time': pd.date_range("1:00", "21:30", freq="30min"),
                   'other-var': range(42)})

def get_day_moment(hour) -> str:
    if 6 <= hour <= 18:
        return 'day'
    return 'night'
df['day-moment'] = df['time'].dt.hour.map(get_day_moment)
df.groupby('day-moment').count()

Upvotes: 2

Imran_Say
Imran_Say

Reputation: 142

***** for pandas dataframe *****
first convert dataarray to dataframe and try following code

df = array.to_dataframe('TEMP')
day = df.between_time('06:00','18:00')
night = df.between_time('00:00','05:59').append(
    df.between_time('18:00','23:59')).sort_index()

Upvotes: 1

Imran_Say
Imran_Say

Reputation: 142

import xarray as xr
import datetime as dt
array = xr.DataArray(
        data=np.linspace(0,30,48),
        coords={"time": pd.date_range('2021-1-1','2021-1-3',periods=48)},
        dims=["time"],
    )
array_day = array[(array.time.dt.hour>=6)&(array.time.dt.hour<=18)]
array_night = array[~((array.time.dt.hour>=6)&(array.time.dt.hour<=18))]

Upvotes: 2

Related Questions