pandas replace_if 使用链

dplyr/magrittr我正在尝试在 pandas 中编写一个类似的链式操作,其中一个步骤包括一个 replace if 命令。


在 R 中,这将是:


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 

但如果这可以成为链条的一部分,我会更喜欢。我找不到replacepandas 的任何替代品,这让我很困惑。我正在寻找类似的东西:


data = pd.read_csv('https://gist.githubusercontent.com/ZeccaLehn/4e06d2575eb9589dbe8c365d61cb056c/raw/64f1660f38ef523b2a1a13be77b002b98665cdfe/mtcars.csv')\

         .rename(columns={'Unnamed: 0':'brand'}, inplace=True) \

         .replace_if(...)


饮歌长啸
浏览 132回答 1
1回答

杨__羊羊

在链中做起来很简单。确保您不在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"])))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python