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(...)
1 回答

杨__羊羊
TA贡献1943条经验 获得超7个赞
在链中做起来很简单。确保您不在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"]))
)
添加回答
举报
0/150
提交
取消