Reputation: 3058
I have a function that returns the index value of a pandas Series
instance comprised of an array of pd.Timestamp
values as an ISO week value.
import numpy as np
import pandas as pd
timestamps = [pd.Timestamp('2014-01-01'), pd.Timestamp('2014-02-01'), pd.Timestamp('2014-02-01')]
quantities = [1.0, 1.0, 1.0]
series = pd.Series(quantities, index=timestamps)
def timestamps_iso() -> np.array:
timestamps_iso = []
for timestamp in series.index:
timestamp_iso = timestamp.isocalendar()[1]
if timestamp_iso == 53: # fix ISO week number 53.
timestamp_iso = np.random.choice([52, 1])
timestamps_iso.append(timestamp_iso)
return np.array(timestamps_iso)
Can this be made quicker, or done in a more pandas style, please? It takes a lot of time when the index is large to run.
Thanks for any help.
Upvotes: 0
Views: 179
Reputation: 11232
Your question says month value, but the code says week value. I assume you're looking for the week value. You can access the week number on a datetime series with .week
:
In [1]: timestamps = [pd.Timestamp('2014-01-01'), pd.Timestamp('2014-02-01'), pd.Timestamp('2014-02-01')]
...: quantities = [1.0, 1.0, 1.0]
...: series = pd.Series(quantities, index=timestamps)
In [2]: series.index.week
Out[2]: Int64Index([1, 5, 5], dtype='int64')
Upvotes: 1