什么是相当于R的`with`的python/pandas?
在 RI 中可以有一个 data.frame 或一个带有多个参数的列表,我可以使用该with函数对它们进行操作。例如:
d <- data.frame(x = 1:3, y = 2:4, z = 3:5)
# I can use:
d$x+d$y*d$z-5
# Or, more simply, I can use:
with(d, x+y*z-5)
# [1] 2 9 18
在 Pandas DataFrame 中,我可以使用:
d = {'x': [1, 2, 3], 'y': [2, 3, 4], 'z': [3, 4, 5]}
df = pd.DataFrame(data=d)
df.x+df.y*df.z-5
# 0 2
# 1 9
# 2 18
# dtype: int64
但是有没有办法做一些“with”之类的语句?
回答
一个想法是DataFrame.eval如果需要处理一些列名称一些简单的算术运算:
print (df.x+df.y*df.z-5)
0 2
1 9
2 18
dtype: int64
print (df.eval('x+y*z-5'))
0 2
1 9
2 18
dtype: int64