【pandas】生日转年龄

         数据挖掘比赛中,获得的数据中可能有个人的生日,在数据分析中并不需要生日,而是需要年龄。不同年龄会呈现不同的状态,比如收入、健康、居住条件等,年龄能够很好的把不同样本的差异性进行大范围的划分。下面讲述如果将生日转年龄:

# -*- coding: utf-8 -*-

# 生成数据
import pandas as pd 
data = {'birth':['2011/12/01','2012/12/02','2012/12/03','2012/12/04','2012/12/05']}
frame = pd.DataFrame(data)
print(frame)
"""
        birth
0  2011/12/01
1  2012/12/02
2  2012/12/03
3  2012/12/04
4  2012/12/05
"""

# 转换为标准时间格式
frame['birth'] = pd.to_datetime(data['birth'])
print(frame)
"""
       birth
0 2011-12-01
1 2012-12-02
2 2012-12-03
3 2012-12-04
4 2012-12-05
"""

# 获取当前年份
import datetime
now_year = datetime.datetime.today().year
print(now_year)
"""
2018
"""

# 生日转换为年龄
frame['age'] = now_year - frame['birth'].datetime.year
print(frame['age'])

猜你喜欢

转载自www.cnblogs.com/wanglei5205/p/8971105.html