相当于 Python pandas 中的 'mutate_at' dplyr 函数

pav*_*omo 2 python r pandas dplyr

并提前感谢您的帮助。

我希望通过将现有列的子集除以另一个现有列(用后缀动态命名)来在 pandas 数据框中创建多个新列。下面是虚拟代码,说明了我想要做的事情的一般要点,除了具有各种转换的 25+ 列之外。

R代码

library(dplyr)

player = c('John','Peter','Michael')
min = c(20, 23, 35)
points = c(10,12,14)
rebounds = c(5,7,9)
assists = c(4,6,7)

df = data.frame(player,min,points,rebounds,assists)

df = df %>%
  mutate_at(vars(points:assists),.funs=funs(per_min=./min))
Run Code Online (Sandbox Code Playgroud)

预期产出

 player min points rebounds assists points_per_min rebounds_per_min assists_per_min
1    John  20     10        5       4      0.5000000        0.2500000       0.2000000
2   Peter  23     12        7       6      0.5217391        0.3043478       0.2608696
3 Michael  35     14        9       7      0.4000000        0.2571429       0.2000000
Run Code Online (Sandbox Code Playgroud)

我知道我可以在 pandas 中重现上述内容,如下所示:

import pandas as pd
data = pd.DataFrame({'player':['John','Peter','Michael'],
                     'min':[20,23,35],
                     'points':[10,12,14],
                     'rebounds':[5,7,9],
                     'assists':[4,6,7]})

df = pd.DataFrame(data)
df['points_per_minute'] = df['points']/df['min']
df['rebounds_per_minute'] = df['rebounds']/df['min']
df['assists_per_minute'] = df['assists']/df['min']

df.head()



 player  min  points  rebounds  assists  points_per_minute  rebounds_per_minute  assists_per_minute
0     John   20      10         5        4           0.500000             0.250000             0.20000
1    Peter   23      12         7        6           0.521739             0.304348             0.26087
2  Michael   35      14         9        7           0.400000             0.257143             0.20000
Run Code Online (Sandbox Code Playgroud)

然而,我必须对 25 个以上的列执行此操作,并进行不同的转换,并且显式命名每个列和操作将变得相当麻烦。有没有熊猫复制这个?

Par*_*ait 5

与基本 R 类似,通过基本算术按列块进行分配。通常,基础 R 可以更好地转换为 Numpy/Pandas。

cols <- c("points", "rebounds", "assists")
df[paste0(cols, "_per_min")] <- df[cols] / df$min
Run Code Online (Sandbox Code Playgroud)

蟒蛇熊猫

cols = ["points", "rebounds", "assists"]
df[[col+'_per_min' for col in cols]] = df[cols].div(df['min'], axis='index')
Run Code Online (Sandbox Code Playgroud)