定期的にデータフレームに取り込む日付があります。データは一般的に整形式ですが、それ以外の日付の列に不良データがある場合があります。
私は常に、解析された9桁の形式の日付を期待します。
(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
(2015, 12, 29, 0, 30, 50, 1, 363, 0)
これをどのように確認して修正する必要がありますか?
私がやりたいのは、日付ではないものを、last_update +更新間隔の1/2を表す変数に基づく日付に置き換えることです。これにより、アイテムは後の関数によって除外されません。
示されているデータは、feedparserからpublished_parsedされています。
import pandas as pd
import datetime
# date with ugly data
df_date_ugly = pd.DataFrame({'date': [
(2015, 12, 29, 0, 30, 50, 1, 363, 0),
(2015, 12, 28, 23, 59, 12, 0, 362, 0),
'None', '',
(2015, 12, 28, 23, 59, 12, 0, 362, 0)
]})
# date is fine
df_date = pd.DataFrame({'date': [
(2015, 12, 29, 0, 30, 50, 1, 363, 0),
(2015, 12, 28, 23, 59, 12, 0, 362, 0),
(2015, 12, 28, 23, 59, 12, 0, 362, 0)
]})
Pseudocode
if the original_date is valid
return original_date
else
return substitute_date
パンダの日付と時刻を操作する場合は、それらを変換するタイムスタンプパンダ使用pandas.to_datetime
。この関数を使用するには、リストを日付と時刻の要素のみを含む文字列に変換します。あなたの場合、長さ9のリストではない値は不良と見なされ、空の文字列に置き換えられます''
。
#convert list into string with date & time
#only elements with lists of length 9 will be parsed
dates_df = df_date_ugly.applymap(lambda x: "{0}/{1}/{2} {3}:{4}:{5}".format(x[0],x[1],x[2], x[3], x[4], x[5]) if len(x)==9 else '')
#convert to a pandas timestamp
dates_df = pd.to_datetime(dates_df['date'], errors = 'coerce'))
date
0 2015-12-29 00:30:50
1 2015-12-28 23:59:12
2 NaT
3 NaT
4 2015-12-28 23:59:12
日付が欠落しているインデックスを見つけますpd.isnull()
。
>>>missing = pd.isnull(dates_df['date']).index
>>>missing
Int64Index([2, 3], dtype='int64')
欠落している日付を2つの日付の中間点として設定するには:
start_date = dates_df.iloc[0,:]
end_date = dates_df.iloc[4,:]
missing_date = start_date + (end_date - start_date)/2
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加