在pandas DataFrame上,我试图计算两个功能之间的变化百分比。例如:
df = pd.DataFrame({'A': [100, 100, 100], 'B': [105, 110, 93], 'C': ['NaN', 102, 'NaN']})
我尝试计算之间的变化df['A'] - df['C']
,但是在我们具有“ NaN”的行上,使用“ B”列中的值。
预期结果:[-5, -2, 7]
因为df['C'].loc[0]
是NaN,所以第一个值是100 - 105
(来自“ B”)。但第二个值是100 -102
。
我认为最简单的方法是将缺失的值替换为另一列Series.fillna
:
#if need replace strings NaN to missing values np.nan
df['C'] = pd.to_numeric(df.C, errors='coerce')
s = df['A'] - df['C'].fillna(df.B)
print (s)
0 -5.0
1 -2.0
2 7.0
dtype: float64
另一个想法,numpy.where
并通过Series.isna
以下方法测试缺失值:
a = np.where(df.C.isna(), df['A'] - df['B'], df['A'] - df['C'])
print (a)
[-5. -2. 7.]
s = df['A'] - np.where(df.C.isna(), df['B'], df['C'])
print (s)
0 -5.0
1 -2.0
2 7.0
Name: A, dtype: float64
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句