質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

pandas

Pandasは、PythonでRにおけるデータフレームに似た型を持たせることができるライブラリです。 行列計算の負担が大幅に軽減されるため、Rで行っていた集計作業をPythonでも比較的簡単に行えます。 データ構造を変更したりデータ分析したりするときにも便利です。

Q&A

解決済

2回答

2572閲覧

生年月日を年齢に変換できない

Pablito

総合スコア71

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

pandas

Pandasは、PythonでRにおけるデータフレームに似た型を持たせることができるライブラリです。 行列計算の負担が大幅に軽減されるため、Rで行っていた集計作業をPythonでも比較的簡単に行えます。 データ構造を変更したりデータ分析したりするときにも便利です。

0グッド

0クリップ

投稿2021/02/08 01:32

前提・実現したいこと

eCommerceのデータから生年月日を抜き取り、購買者の年代を調べたいと思っております。
そこで今まで下記のコードを実行し、うまくできていたのですが、
今回、下記のエラーが起きるようになりました。

検索をしていてもよく分からず、
お力添えを頂けないでしょうか。

発生している問題・エラーメッセージ

--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-7-d2663eeb813f> in <module> 4 return int((today - birthday) / 10000) 5 ----> 6 df['年齢'] = df['生年月日'].apply(lambda date: getAge(date)) 7 df c:\users\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds) 4106 else: 4107 values = self.astype(object)._values -> 4108 mapped = lib.map_infer(values, f, convert=convert_dtype) 4109 4110 if len(mapped) and isinstance(mapped[0], Series): pandas\_libs\lib.pyx in pandas._libs.lib.map_infer() <ipython-input-7-d2663eeb813f> in <lambda>(date) 4 return int((today - birthday) / 10000) 5 ----> 6 df['年齢'] = df['生年月日'].apply(lambda date: getAge(date)) 7 df <ipython-input-7-d2663eeb813f> in getAge(birthday) 1 def getAge(birthday): 2 today = int(pd.to_datetime('today').strftime('%Y%m%d')) ----> 3 birthday = int(birthday.strftime('%Y%m%d')) 4 return int((today - birthday) / 10000) 5 pandas\_libs\tslibs\nattype.pyx in pandas._libs.tslibs.nattype._make_error_func.f() ValueError: NaTType does not support strftime

該当のソースコード

Python

1import pandas as pd 2import datetime as dt 3 4path = r'G:\fs2_20210205120821.csv' 5df = pd.read_csv(path, sep=',', encoding='cp932', dtype={'会員ID': object}) 6df.info() 7 8***************************************** 9<class 'pandas.core.frame.DataFrame'> 10RangeIndex: 47 entries, 0 to 46 11Data columns (total 27 columns): 12 # Column Non-Null Count Dtype 13--- ------ -------------- ----- 14 0 注文日時 47 non-null object 15 1 請求合計金額 47 non-null int64 16 2 総合計金額 47 non-null int64 17 3 商品合計金額 47 non-null int64 18 4 消費税合計 47 non-null int64 19 5 包装手数料 47 non-null int64 20 6 送料 47 non-null int64 21 7 決済手数料 47 non-null int64 22 8 クール便手数料 47 non-null int64 23 9 その他手数料 47 non-null int64 24 10 決済方法 47 non-null object 25 11 購入経路区分 47 non-null object 26 12 会員ID 36 non-null object 27 13 氏名(姓) 47 non-null object 28 14 氏名(名) 47 non-null object 29 15 地域区分 47 non-null object 30 16 都道府県区分 47 non-null object 31 17 性別区分 11 non-null object 32 18 生年月日 11 non-null object 33 19 クール便使用フラグ 47 non-null object 34 20 送り状番号 47 non-null object 35 21 お届け希望日 4 non-null object 36 22 お届け希望時間 11 non-null object 37 23 商品番号 47 non-null object 38 24 商品名 47 non-null object 39 25 販売単価 47 non-null int64 40 26 購入数量 47 non-null int64 41dtypes: int64(11), object(16) 42memory usage: 10.0+ KB 43***************************************** 44 45df.head() 46****************************************** 47 48 注文日時 請求合計金額 総合計金額 商品合計金額 消費税合計 包装手数料 送料 決済手数料 クール便手数料 その他手数料 ... 性別区分 生年月日 クール便使用フラグ 送り状番号 お届け希望日 お届け希望時間 商品番号 商品名 販売単価 購入数量 490 2021/01/31 17:10:55 4714 4714 2964 0 0 1200 330 220 0 ... NaN NaN クール便 380237213484 NaN 午前中(8時~12時) gap34(1袋) 494 6 50 51******************************************* 52 53df['生年月日'] = df['生年月日'].str.replace('生', '') 54df['生年月日'].head() 55 56******************************************* 570 NaN 581 1959/09/13 592 NaN 603 NaN 614 NaN 62Name: 生年月日, dtype: object 63******************************************* 64 65df['生年月日'] = df['生年月日'].apply(pd.to_datetime, errors='coerce') 66df[['生年月日']].head() 67 68********************* 69生年月日 700 NaT 711 1959-09-13 722 NaT 733 NaT 744 NaT 7511 non-null datetime64[ns] 76********************* 77 78birth_date = df.dropna(subset=['生年月日']) 79 80def getAge(birthday): 81 today = int(pd.to_datetime('today').strftime('%Y%m%d')) 82 birthday = int(birthday.strftime('%Y%m%d')) 83 return int((today - birthday) / 10000) 84 85df['年齢'] = df['生年月日'].apply(lambda date: getAge(date)) 86df

試したこと

https://teratail.com/questions/126010
こちらを参考にし、Forループを試しましたが、
上手くいきませんでした。

補足情報(FW/ツールのバージョンなど)

pandas 1.2.1
DateTime 4.3
Python 3.8.3

何卒宜しくお願い致します!

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

meg_

2021/02/08 01:38

生年月日が空(未入力?)のデータがありませんか?
Pablito

2021/02/08 01:42

ご質問ありがとうございます。 空のデータは下記のコードで消している認識ですが、確認はしてなかったです! birth_date = df.dropna(subset=['生年月日'])
Pablito

2021/02/08 01:45

確認したところ、やはり欠損値はないようです。 print(birth_date.isnull().sum()) **************** 生年月日 0 ****************
kirara0048

2021/02/08 01:57

`df['生年月日']`に欠損値があるのでしょう。
Pablito

2021/02/08 02:00

皆様ありがとうございました。 df['年齢'] = birth_date['生年月日'].apply(lambda date: getAge(date)) df このように変換したら実行できました。 ご協力ありがとうございました。
guest

回答2

0

ベストアンサー

birth_date = df.dropna(subset=['生年月日'])で欠損値落としたbirth_dateを作成したのに、以降の処理をbirth_dateではなくdfに対して行っているので、欠損値が残っていてエラーになっています。

以下、動作確認

python3

1import io 2import pandas as pd 3data = """生年月日 40 NaN 51 1959/09/13 62 NaN 73 NaN 84 NaN""" 9 10df = pd.read_table(io.StringIO(data), delimiter="\s+") 11print(df) 12# 生年月日 13# 0 NaN 14# 1 1959/09/13 15# 2 NaN 16# 3 NaN 17# 4 NaN 18 19df['生年月日'] = df['生年月日'].apply(pd.to_datetime, errors='coerce') 20print(df) 21 22birth_date = df.dropna(subset=['生年月日']) 23print(birth_date) 24# 生年月日 25# 1 1959-09-13 26 27 28def getAge(birthday): 29 today = int(pd.to_datetime('today').strftime('%Y%m%d')) 30 birthday = int(birthday.strftime('%Y%m%d')) 31 return int((today - birthday) / 10000) 32 33birth_date['年齢'] = birth_date['生年月日'].apply(lambda date: getAge(date)) 34print(birth_date) 35 36# 生年月日 年齢 37# 1 1959-09-13 61

投稿2021/02/08 02:00

jeanbiego

総合スコア3966

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Pablito

2021/02/08 02:02

ご回答ありがとうございます。 ご教示頂いたやり方で解決できました。 ありがとうございました。
guest

0

df['年齢'] = birth_date['生年月日'].apply(lambda date: getAge(date))
df
で実行できました。

投稿2021/02/08 02:00

Pablito

総合スコア71

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

meg_

2021/02/08 02:17

jeanbiegoさんの回答が役に立ったのであればベストアンサーにするべきではないでしょうか?
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問