Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new Pandas Column with just the year of another column

Tags:

python

pandas

I have the following df where 'per_end_date' is a Datetime object.

zacks_mktv_df[:4]

ticker | per_end_date | mkt_val
--------------------------------
A      | 2016-12-31   | 14648.84
A      | 2015-12-31   | 13704.02
A      | 2014-12-31   | 13751.83

I want to grab the year from every row in 'per_end_date' column and make another row out of it so for my table above it would look like.

ticker | per_end_date | mkt_val  |
--------------------------------------------
A      | 2016-12-31   | 14648.84 | 2016
A      | 2015-12-31   | 13704.02 | 2015
A      | 2014-12-31   | 13751.83 | 2014

I tried this.

zacks_mktv_df['per_fisc_year'] = zacks_mktv_df[zacks_mktv_df.per_end_date.dt.year]

Getting the folowing error:

IndexError: indices are out-of-bounds
like image 996
TEKOrchestrator Avatar asked Jan 18 '26 17:01

TEKOrchestrator


1 Answers

You could use

zacks_mktv_df['per_fisc_year'] = zacks_mktv_df['per_end_date'].dt.year

If the column per_end_date is eg. datetime64.

like image 137
Jan Avatar answered Jan 21 '26 08:01

Jan