Python 如果使用链条,请更换_
我试图在pandas中编写一个类似于dplyr/magrittr的链式操作,其中一个步骤包括一个replace if命令 在R中,这将是:Python 如果使用链条,请更换_,python,r,pandas,dplyr,Python,R,Pandas,Dplyr,我试图在pandas中编写一个类似于dplyr/magrittr的链式操作,其中一个步骤包括一个replace if命令 在R中,这将是: mtcars %>% mutate(mpg=replace(mpg, cyl==4, -99)) %>% as.data.frame() 在python中,我可以执行以下操作: data = pd.read_csv('https://gist.githubusercontent.com/ZeccaLehn/4e06d2575
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, -99)) %>%
as.data.frame()
在python中,我可以执行以下操作:
data = pd.read_csv('https://gist.githubusercontent.com/ZeccaLehn/4e06d2575eb9589dbe8c365d61cb056c/raw/64f1660f38ef523b2a1a13be77b002b98665cdfe/mtcars.csv')\
.rename(columns={'Unnamed: 0':'brand'}, inplace=True)
data.loc[df.cyl == 4, 'mpg'] = -99
但我更希望这是一条链的一部分。我找不到熊猫的替代品,这让我很困惑。我正在寻找类似于:
data = pd.read_csv('https://gist.githubusercontent.com/ZeccaLehn/4e06d2575eb9589dbe8c365d61cb056c/raw/64f1660f38ef523b2a1a13be77b002b98665cdfe/mtcars.csv')\
.rename(columns={'Unnamed: 0':'brand'}, inplace=True) \
.replace_if(...)
在一个链中做起来很简单。确保不要在链中使用
inplace=
,因为它不会将数据帧返回到链中的下一个对象
(pd.read_csv('https://gist.githubusercontent.com/ZeccaLehn/4e06d2575eb9589dbe8c365d61cb056c/raw/64f1660f38ef523b2a1a13be77b002b98665cdfe/mtcars.csv')
.rename(columns={'Unnamed: 0':'brand'})
.assign(mpg=lambda dfa: np.where(dfa["cyl"]==4, -99, dfa["mpg"]))
)
使用
Series.where
或numpy.where
与DataFrame.assign
同时,不要在链中使用inplace=True
。在链中where
或assign
将如何工作?因为读取发生在同一个操作上,所以很难引用所需的内容。在这种情况下,我认为“想要链”使这个操作复杂得多,而不是将其拆分。@ALollz withlambda
。。?并使用掩码
。链接类似.assign(mpg=lambda x:x['mpg'].mask(x['cyl']==4,-99))
或更简单的.assign(mpg=lambda x:np.where(x.cyl==4,-99,x.mpg))