Pandas np.其中条件第一个实例ok,第二个实例抛出错误
我有一个pandas数据框,其中有一个日期列,包含第一天(“欧洲”)和第一个月(美国)的日期。我有一个单独的int类型列,其中包含“year”值。df.year2017的日期字符串为第一天 我使用一个np.where条件将日期字符串中的月和日分隔成单独的列,以在其后构建日期时间。所以我有这些数据:Pandas np.其中条件第一个实例ok,第二个实例抛出错误,pandas,numpy,Pandas,Numpy,我有一个pandas数据框,其中有一个日期列,包含第一天(“欧洲”)和第一个月(美国)的日期。我有一个单独的int类型列,其中包含“year”值。df.year2017的日期字符串为第一天 我使用一个np.where条件将日期字符串中的月和日分隔成单独的列,以在其后构建日期时间。所以我有这些数据: 'year' 'number' 'date' 2016 75 01/05/2017 00:00 2016 75 01/06/2017 00:00 2016 75 01/06/2
'year' 'number' 'date'
2016 75 01/05/2017 00:00
2016 75 01/06/2017 00:00
2016 75 01/06/2017 00:00
2016 75 01/06/2017 00:00
2016 75 01/06/2017 00:00
2016 75 01/09/2017 00:00
2016 75 01/09/2017 00:00
2016 75 01/10/2017 00:00
2016 75 01/10/2017 00:00
2017 0 01/01/2017 00:00
2017 0 01/01/2017 00:00
2017 0 01/01/2017 00:00
2017 0 01/01/2017 00:00
2017 0 02/01/2017 00:00
2017 0 03/01/2017 00:00
2017 0 04/01/2017 00:00
2017 0 04/01/2017 00:00
2017 0 04/01/2017 00:00
2017 0 04/01/2017 00:00
2017 0 05/01/2017 00:00
我已经使用它创建了月份值:
df['dt_mo'] = np.where(df.year<2017,df.date.str.extract(r'(\d+)\/\d+\/\d+'), df.date.str.extract(r'\d+\/(\d+)\/\d+'))
或
(2)df['dt_dy']=np.where(df.year似乎您最终想要创建datetime
,所以从一开始就用np.where
指定不同的格式创建它。如果您需要天数,现在可以使用datetime
访问器
import numpy as np
import pandas as pd
df['my_date'] = np.where(df.year < 2017,
pd.to_datetime(df.date, format='%m/%d/%Y %H:%M', errors='coerce'),
pd.to_datetime(df.date, format='%d/%m/%Y %H:%M', errors='coerce'))
太棒了!我还有另外两列,其中包含零星的开始时间和结束时间。在创建这些时间后,我可以将它们中的一个或两个添加到相应的日期时间吗?@jrbwt当然可以。只要您将它们转换为timedelta
或datetime
,您就可以添加它们。
(2)df['dt_dy'] = np.where(df.year<2017,df.date.str.extract(r'\d+\/(\d+)\/\d+'), df.date.str.extract(r'(\d+)\/\d+\/\d+'))
import numpy as np
import pandas as pd
df['my_date'] = np.where(df.year < 2017,
pd.to_datetime(df.date, format='%m/%d/%Y %H:%M', errors='coerce'),
pd.to_datetime(df.date, format='%d/%m/%Y %H:%M', errors='coerce'))
year number date my_date
0 2016 75 01/05/2017 00:00 2017-01-05
1 2016 75 01/06/2017 00:00 2017-01-06
2 2016 75 01/06/2017 00:00 2017-01-06
3 2016 75 01/06/2017 00:00 2017-01-06
4 2016 75 01/06/2017 00:00 2017-01-06
5 2016 75 01/09/2017 00:00 2017-01-09
6 2016 75 01/09/2017 00:00 2017-01-09
7 2016 75 01/10/2017 00:00 2017-01-10
8 2016 75 01/10/2017 00:00 2017-01-10
9 2017 0 01/01/2017 00:00 2017-01-01
10 2017 0 01/01/2017 00:00 2017-01-01
11 2017 0 01/01/2017 00:00 2017-01-01
12 2017 0 01/01/2017 00:00 2017-01-01
13 2017 0 02/01/2017 00:00 2017-01-02
14 2017 0 03/01/2017 00:00 2017-01-03
15 2017 0 04/01/2017 00:00 2017-01-04
16 2017 0 04/01/2017 00:00 2017-01-04
17 2017 0 04/01/2017 00:00 2017-01-04
18 2017 0 04/01/2017 00:00 2017-01-04
19 2017 0 05/01/2017 00:00 2017-01-05