我有两列,
AnalyseDatum_calc erstellt am
0 05.01.2015 31.10.2014
1 SN not found 07.01.2015
2 05.01.2015 31.10.2014
3 05.01.2015 SN not found
4 05.01.2015 SN not found
5 05.01.2015 07.01.2015
6 SN not found 31.10.2014
7 SN not found 07.01.2015
8 05.01.2015 09.12.2014
我想比较一下,如果两列都是date,那么date-date=days。
这是formel:
df4['Tage SM-Analyse_helper'] = np.where(((df4['AnalyseDatum_calc'] != 'SN not found') & (df4['erstellt am'] != 'SN not found')), (pd.to_datetime(df4['AnalyseDatum_calc'], format='%d.%m.%Y') - pd.to_datetime(df4['erstellt am'], format='%d.%m.%Y')).dt.days,'NOK')
我收到错误:
ValueError: time data 'SN not found' does not match format '%d.%m.%Y' (match)
我做错了什么?非常感谢的帮助
您可以使用pd.to_datetime
和errors='coerce'
选项:
(pd.to_datetime(df['AnalyseDatum_calc'], dayfirst=True,errors='coerce')
- pd.to_datetime(df['erstellt am'], dayfirst=True,errors='coerce')
)
输出:
0 66 days
1 NaT
2 66 days
3 NaT
4 NaT
5 -2 days
6 NaT
7 NaT
8 27 days
dtype: timedelta64[ns]
尝试以下操作:
import pandas as pd
import datetime as dt
def validate_date(inp, date_format):
try:
return dt.datetime.strptime(inp, date_format)
except ValueError:
return None
data = {
'AnalyseDatum_calc': ['05.01.2015', 'SN not found', '05.01.2015', '05.01.2015', '05.01.2015', '05.01.2015', 'SN not found', 'SN not found', '05.01.2015'],
'erstellt am': ['31.10.2014', '07.01.2015', '31.10.2014', 'SN not found', 'SN not found', '07.01.2015', '31.10.2014', '07.01.2015', '09.12.2014'],
}
df = pd.DataFrame(data)
df['date_diff'] = df['AnalyseDatum_calc'].apply(lambda x: validate_date(x, '%d.%m.%Y')) - df['erstellt am'].apply(lambda x: validate_date(x, '%d.%m.%Y'))