2

I have a data set

id     Category    Date
1       Sick      2016-10-10
                  12:10:21
2       Active    2017-09-08
                  11:09:06
3       Weak      2018-11-12
                  06:10:04

Now i want to add a new column which only has year in the data set using pandas?

0

2 Answers 2

1

You could do:

import pandas as pd
data = [[1, 'Sick  ', '2016-10-10 12:10:21'],
        [2, 'Active', '2017-09-08 11:09:06'],
        [3, 'Weak  ', '2018-11-12 06:10:04']]

df = pd.DataFrame(data=data, columns=['id', 'category', 'date'])

df['year'] =  pd.to_datetime(df['date']).dt.year

print(df)

Output

id category                 date  year
0   1   Sick    2016-10-10 12:10:21  2016
1   2   Active  2017-09-08 11:09:06  2017
2   3   Weak    2018-11-12 06:10:04  2018
Sign up to request clarification or add additional context in comments.

1 Comment

@shrutyam Glad I could help, if my answer was helpful please consider marking it as accepted.
1

you can just do df['year'] = pd.DatetimeIndex(df['Date']).year

Output:

    id  category    Date                year
0   1   Sick       2016-10-10 12:10:21  2016
1   2   Active     2017-09-08 11:09:06  2017
2   3   Weak       2018-11-12 06:10:04  2018

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.