python - 显示第一年并每年递增
问题描述
为什么 pd.date_range 按天递增时显示 1/1/1970 但按年递增时显示年末
import pandas as pd
import numpy as np
n = 100
randoms = pd.DataFrame(dict(
Rand1=np.random.normal(loc=1,scale=2,size=n),
Rand2=np.random.normal(1,2,size=n),
Rand3=np.random.normal(1,2,size=n)
))
randoms['Date'] = pd.date_range(start='1/1/1970', periods=n, freq='y')
print(randoms)
这是我的输出,但我需要显示一年中的第一天而不是最后一天的日期
Rand1 Rand2 Rand3 Date
0 1.139258 -1.390884 2.032142 1970-01-31
1 0.386232 2.029267 -1.499711 1970-02-28
2 3.314543 1.671777 -0.069631 1970-03-31
3 -1.426235 1.543605 1.643718 1970-04-30
4 -2.286934 3.986482 1.763480 1970-05-31
.. ... ... ... ...
95 2.991113 1.723248 1.053139 1977-12-31
96 2.906345 0.268920 4.029668 1978-01-31
97 2.162349 2.251527 3.456534 1978-02-28
98 -2.415481 2.097225 -4.070858 1978-03-31
99 4.142901 1.051146 -3.559649 1978-04-30
解决方案
那是因为freq=y
手段year end frequency
。如果需要year start frequency
,请ys
像这样使用:
randoms['Date'] = pd.date_range(start='1/1/1970', periods=n, freq='YS')
产生这个:
Rand1 Rand2 Rand3 Date
0 -0.185472 1.079234 3.568975 1970-01-01
1 2.395674 0.506991 1.342406 1971-01-01
2 2.850708 1.185848 4.090613 1972-01-01
3 -0.272404 1.071543 3.011254 1973-01-01
4 -0.116338 0.563471 -0.114609 1974-01-01
您可以从此处查看频率别名的完整列表。