search
LoginSignup
14
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

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

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

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

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
What you can do with signing up
14
Help us understand the problem. What are the problem?