我有这样的数据框:

    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列转换为dtype datetime,然后可以将.dt访问器用于year和month属性:

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]

10-06 10:47