2024-04-26 00:38:47 发布
网友
我有这样的数据帧:
month items 0 1962-01-01 589 1 1962-02-01 561 2 1962-03-01 640 3 1962-04-01 656 4 1962-05-01 723
我需要从这个数据框中获取年或月并创建数组,但我不知道如何做到这一点。你知道吗
预期结果:
years = [1962, 1962, 1962....] monthes = [1, 2, 3, 4, 5.....]
你能帮我吗?你知道吗
假设这是pandas,您可能需要将month列转换为数据类型datetime,然后您就可以对year和month属性使用.dt访问器:
pandas
datetime
.dt
In [33]: df['month'] = pd.to_datetime(df['month']) df.info() <class 'pandas.core.frame.DataFrame'> Int64Index: 5 entries, 0 to 4 Data columns (total 2 columns): month 5 non-null datetime64[ns] items 5 non-null int64 dtypes: datetime64[ns](1), int64(1) memory usage: 120.0 bytes In [35]: years = df['month'].dt.year.tolist() months = df['month'].dt.month.tolist() print(years) print(months) [1962, 1962, 1962, 1962, 1962] [1, 2, 3, 4, 5]
假设这是
pandas
,您可能需要将month列转换为数据类型datetime
,然后您就可以对year和month属性使用.dt
访问器:相关问题 更多 >
编程相关推荐