如何根据输入年份在一年中的日子生成数据框架?
我想生成一个数据框,根据指定年份将一年中的天数附加到第一列。我该怎么做?我正在使用 pandas date_range
模块。
这是我尝试过的:
#Import modules
import pandas as pd
import numpy as np
import datetime as dt
#Specify the year
year = 1976
#Create dataframe
df = pd.Series(pd.date_range(year, periods=365, freq='D'))
print(df)
结果:
0 1970-01-01 00:00:00.000001976
1 1970-01-02 00:00:00.000001976
2 1970-01-03 00:00:00.000001976
3 1970-01-04 00:00:00.000001976
4 1970-01-05 00:00:00.000001976
...
360 1970-12-27 00:00:00.000001976
361 1970-12-28 00:00:00.000001976
362 1970-12-29 00:00:00.000001976
363 1970-12-30 00:00:00.000001976
364 1970-12-31 00:00:00.000001976
Length: 365, dtype: datetime64[ns]
这里的年份是错误的,我需要它是 1976 年。此外,我需要的只是一个“一年中的某一天”列,其中的行数与该中的天数相对应年(这将考虑闰年)。我该如何解决这个问题?
输出应该是一个如下所示的数据框(它应该一直延伸到一年的最后一天):
d = {
'year': [1976, 1976, 1976, 1976, 1976, 1976],
'day of the year': [1, 2, 3, 4, 5, 6]
}
df1 = pd.DataFrame(data=d)
df1
I would like to generate a dataframe with the days of the year appended to the first column based on a specified year. How can I do this? I am using the pandas date_range
module.
Here is what I have tried:
#Import modules
import pandas as pd
import numpy as np
import datetime as dt
#Specify the year
year = 1976
#Create dataframe
df = pd.Series(pd.date_range(year, periods=365, freq='D'))
print(df)
The result:
0 1970-01-01 00:00:00.000001976
1 1970-01-02 00:00:00.000001976
2 1970-01-03 00:00:00.000001976
3 1970-01-04 00:00:00.000001976
4 1970-01-05 00:00:00.000001976
...
360 1970-12-27 00:00:00.000001976
361 1970-12-28 00:00:00.000001976
362 1970-12-29 00:00:00.000001976
363 1970-12-30 00:00:00.000001976
364 1970-12-31 00:00:00.000001976
Length: 365, dtype: datetime64[ns]
The year is wrong here, I need it to be 1976. Additionally, all I need is a "Day of the Year" column with the number of rows corresponding to the number of days in the year (this would account for leap years). How can I fix this?
The output should be a dataframe that looks like this (it should extend all the way to the last day of the year):
d = {
'year': [1976, 1976, 1976, 1976, 1976, 1976],
'day of the year': [1, 2, 3, 4, 5, 6]
}
df1 = pd.DataFrame(data=d)
df1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
或者
Or