简体   繁体   中英

What is a python/pandas equivalent to R's `with`?

In R I can have a data.frame or a list with several arguments, and I can operate on them using the with function. For example:

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

In pandas DataFrame I can use:

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

But is there a way to do some "with" like statement?

One idea is use DataFrame.eval if need processing some columns names some simple arithmetic operations:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM