Woo*_*ide 6 numpy where pandas
我喜欢np.where,但从未完全掌握它.
我有一个数据帧让我们说它看起来像这样:
import pandas as pd
import numpy as np
from numpy import nan as NA
DF = pd.DataFrame({'a' : [ 3, 0, 1, 0, 1, 14, 2, 0, 0, 0, 0],
'b' : [ 3, 0, 1, 0, 1, 14, 2, 0, 0, 0, 0],
'c' : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'd' : [5, 1, 2 ,1, 1 ,22, 30, 1, 0, 0, 0]})
Run Code Online (Sandbox Code Playgroud)
现在我要做的是在所有行值为零时用NaN值替换0值.关键是我想在所有行值都不为零的情况下维护行中的其他任何值.
我想做这样的事情:
cols = ['a', 'b', 'c', 'd']
condition = (DF[cols] == 0).all(axis=1)
for col in cols:
DF[col] = np.where(condition, NA, ???)
Run Code Online (Sandbox Code Playgroud)
我把??? 表示如果条件为False,我不知道放在那里的值是什么,我只想保留那里已有的东西.这可能与np.where,或我应该使用另一种技术?
对于这种任务,有一种pandas.Series方法(where顺便说一下).起初看起来有点落后,但是来自文档.
Series.where(cond,other = nan,inplace = False,axis = None,level = None,try_cast = False,raise_on_error = True)
返回与self相同形状的对象,其对应的条目来自self,其中cond为True,否则来自其他.
所以,你的榜样将成为
cols = ['a', 'b', 'c', 'd']
condition = (DF[cols] == 0).all(axis=1)
for col in cols:
DF[col].where(~condition, np.nan, inplace=True)
Run Code Online (Sandbox Code Playgroud)
但是,如果你要做的就是用特定的列集替换所有零的行NA,你可以改为
DF.loc[condition, cols] = NA
Run Code Online (Sandbox Code Playgroud)
编辑
要回答您的原始问题,请np.where遵循与其他阵列操作相同的广播规则,以便替换???为DF[col],将您的示例更改为:
cols = ['a', 'b', 'c', 'd']
condition = (DF[cols] == 0).all(axis=1)
for col in cols:
DF[col] = np.where(condition, NA, DF[col])
Run Code Online (Sandbox Code Playgroud)