Alex Savin Alex Savin - 2 months ago 10
Python Question

How to extract date form data frame column?

I have data frame like that:

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


I need to get year or month from this data frame and create array, but I don't know how to do that.

expected result:

years = [1962, 1962, 1962....]
monthes = [1, 2, 3, 4, 5.....]


Can you help me?

Answer

Assuming this is pandas you may need to convert the month column to dtype datetime and then you can use .dt accessor for the year and month attributes:

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]