LoginSignup
18
15

More than 5 years have passed since last update.

誕生日から年齢を計算する(pandas編)

Last updated at Posted at 2016-12-19

年齢計算の手法自体は古から伝わるものです。

import pandas as pd

today = int(pd.to_datetime('today').strftime('%Y%m%d'))
birthday = int(pd.to_datetime('1979/5/14').strftime('%Y%m%d'))
int((today - birthday) / 10000)

これだけならわざわざpandas使うまでもないですが、
to_datetimeがかしこいのと、Dataframeと連携しやすいので乱用中です。

せっかくなのでDataframeとの連携例も。

import pandas as pd

# 誕生日のリスト
df = pd.DataFrame([
        {"name":"tarou", "birthday":pd.to_datetime('1979/5/14')},
        {"name":"jirou", "birthday":pd.to_datetime('1981/9/10')},
        {"name":"saburou", "birthday":pd.to_datetime('1985/6/20')},
    ])
df
birthday name
0 1979-05-14 tarou
1 1981-09-10 jirou
2 1985-06-20 saburou
# 使いやすいように、今回の手法を関数化
def getAge(birthday):
    today    = int(pd.to_datetime('today').strftime('%Y%m%d'))
    birthday = int(birthday.strftime('%Y%m%d'))
    return int((today - birthday) / 10000)

df['age'] = df['birthday'].apply(lambda date: getAge(date))
df

簡単に「年齢」列を追加できました。

birthday name age
0 1979-05-14 tarou 37
1 1981-09-10 jirou 35
2 1985-06-20 saburou 31
18
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
15