我尝试通过以下方式将新列添加到具有列表理解和if语句的DataFrame中:
SD['Ln(aT) ANALYTIC'] = [x + 1 for x in SD['T'] if SD['T'] >= SD['TG']]
我得到这个错误:
The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().
我不知道该如何处理。
有什么建议吗?
编辑: DataFrame如下:
答案 0 :(得分:2)
将numpy.where
与布尔掩码一起使用:
mask = SD['T'] >= SD['TG']
SD['Ln(aT) ANALYTIC'] = np.where(mask, SD['T'] + 1, SD['T'])
或者:
SD['Ln(aT) ANALYTIC'] = np.where(mask, SD['T'] + 1, np.nan)
可以进行列表拼写,但是很慢:
SD['Ln(aT) ANALYTIC1'] = [i + 1 if i >= j else i for i, j in zip(SD['T'], SD['TG'])]
SD = pd.DataFrame({'T': [1,2,3],
'TG':[2,5,1]})
#[3000 rows x 2 columns]
SD = pd.concat([SD] * 1000, ignore_index=True)
In [294]: %timeit SD['Ln(aT) ANALYTIC1'] = [i + 1 if i >= j else i for i, j in zip(SD['T'], SD['TG'])]
1.18 ms ± 82.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [295]: %timeit SD['Ln(aT) ANALYTIC2'] = np.where(SD['T'] >= SD['TG'], SD['T'] + 1, SD['T'])
511 µs ± 16.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)