使用NaN的Python pandas DataFrame操作

罗汉

在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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在 Pandas DataFrame 操作中处理零或 NaN

写入操作后,Pandas DataFrame包含NaN

Python Pandas中的DataFrame中的日期操作?

pandas DataFrame(简单?)操作

我如何在pandas / dataframe中执行以下python操作

使用pandas DataFrame.apply进行列操作

分组并在Pandas Dataframe上使用APPLY和MAX操作

使用其索引对 Pandas Dataframe 列进行操作

Pandas:对 NaN 值的“或”操作

在Python Pandas中的DataFrame中使用日期进行数据操作?

在 Pandas 的 DataFrame 中操作值

Python pandas.DataFrame:根据条件使整行为NaN

Python Pandas DataFrame用其他系列填充NaN

Python Pandas-无法合并多个返回NaN的DataFrame

Python Pandas Dataframe用列表中的值替换NaN

使用列条件删除包含 Pandas DataFrame 中的行的 NaN

使用Python Pandas用非NaN的值填充NaN值

Pandas 的 Python 列表操作

如何对包含 Python 中元组列表的 Pandas DataFrame 列执行各种操作?

像在 Python 中操作 pandas.Dataframe 一样快地查询 SQLite DB

pandas.DataFrame为什么使用括号来包装操作以进行按位比较

如何在Pandas DataFrame中使用列表中的项目进行“与”操作

Pandas DataFrame,不能使用内置函数-不支持的操作数类型

Pandas:使用 nans 操作

对Pandas DataFrame的不同列执行不同的操作

操作包含Twitter API词典的Pandas DataFrame

以Date为索引的Pandas DataFrame操作

如何对 Pandas DataFrame 上的类别执行操作

使用 Pandas 在 Python 中分组列操作