pandas生日转年龄

Posted wanglei5205

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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])

以上是关于pandas生日转年龄的主要内容,如果未能解决你的问题,请参考以下文章