我有两家年终不同的公司(1/31和12/31),我想获取各自季度中发生的指标的平均值。在此示例中,我为两家公司创建了一个2016年至2017年的8个季度结束日期的DataFrame:
comp1 = pd.date_range('1/31/2016', periods=8, freq='3M')
comp2 = pd.date_range('1/31/2016', periods=8, freq='Q')
quarters = pd.DataFrame([1] * 8 + [2] * 8, index=comp1.append(comp2), columns=['company'])
Run Code Online (Sandbox Code Playgroud)
这是组成的数据,其中有两个值(A和B),分别在2016年和2017年的每个月内的随机日期进行测量:
values = np.transpose([np.arange(1, 25), np.arange(1, 25) * 11])
dates = ['2016-01-14', '2016-02-03', '2016-03-15', '2016-04-04',
'2016-05-30', '2016-06-11', '2016-07-18', '2016-08-08',
'2016-09-09', '2016-10-10', '2016-11-01', '2016-12-24',
'2017-01-30', '2017-02-19', '2017-03-13', '2017-04-24',
'2017-05-31', '2017-06-02', '2017-07-28', '2017-08-23',
'2017-09-04', '2017-10-30', '2017-11-11', '2017-12-06']
df = pd.DataFrame(values, index=pd.DatetimeIndex(dates), columns=['A', 'B'])
Run Code Online (Sandbox Code Playgroud)
数据如下所示:
A B
2016-01-14 1 11
2016-02-03 2 22
2016-03-15 3 33
2016-04-04 4 44
2016-05-30 5 …Run Code Online (Sandbox Code Playgroud) 我正在使用index()字符串来查找子字符串的出现.
当字符串中不存在子字符串时,我得到:
"ValueError: substring not found".
Run Code Online (Sandbox Code Playgroud)
我希望我的程序能够识别何时发生这种情况,但我不知道如何将其ValueError转化为有用的东西.例如,我如何ValueError在if声明中使用a ?