我有一个函数返回一个由Series
值数组组成的熊猫pd.Timestamp
实例的索引值作为ISO周值。
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)
请问这可以做得更快,还是可以采用更熊猫的风格?当索引很大时,要花很多时间。
感谢您的帮助。
答案 0 :(得分:1)
您的问题表示月份值,但代码表示星期值。我认为您正在寻找星期值。您可以使用.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')