[英]R with function in python
In R
, I can use with(obj, a + b + c + d)
instead of obj$a + obj$b + obj$c + obj$d
, where obj
can be a list
or data.frame
. 在
R
,我可以使用with(obj, a + b + c + d)
而不是obj$a + obj$b + obj$c + obj$d
,其中obj
可以是list
或data.frame
。
Is there any similar function for dict
, pandas.Series
, pandas.DataFrame
in python? 在python中有没有类似的
dict
, pandas.Series
, pandas.DataFrame
函数?
In a way, no. 在某种程度上,没有。 But there are lots of somewhat similar alternatives.
但是有很多有些类似的选择。 The
with
function of R seems quite versatile, so in Python one has to replace it case by case. R的
with
函数似乎非常通用,因此在Python中必须逐个替换它。
You could use itemgetter()
for simple collections: 您可以将
itemgetter()
用于简单集合:
In [1]: d = dict(a=1, b=2, c=3, d=4)
In [2]: from operator import itemgetter
In [3]: sum(itemgetter('a', 'b', 'c', 'd')(d))
Out[3]: 10
Or attrgetter()
for, again simple, objects: 或
attrgetter()
,再次简单,对象:
In [4]: from collections import namedtuple
In [5]: from operator import attrgetter
In [8]: sum(attrgetter('a', 'b', 'c', 'd')(
namedtuple('sdf', 'a b c d')(1, 2, 3, 4)))
Out[8]: 10
Pandas' DataFrame
s support directly accessing specific columns and applying operations on them. Pandas的
DataFrame
支持直接访问特定列并对其应用操作。 Summing is an easy example, as it has a function as is: 求和是一个简单的例子,因为它具有以下功能:
In [10]: df = pd.DataFrame({'A': range(10), 'B': range(10), 'C': range(10)})
In [21]: df[['A', 'B']].sum(axis=1) # row sums
Out[21]:
0 0
1 2
2 4
3 6
4 8
5 10
6 12
7 14
8 16
9 18
dtype: int64
There's also DataFrame.eval
, which is closest to what you're after, I think: 还有
DataFrame.eval
,它与您所追求的最接近,我认为:
Evaluate an expression in the context of the calling DataFrame instance.
在调用DataFrame实例的上下文中计算表达式。
In [9]: df.eval('(A + B) ** C')
Out[9]:
0 1
1 2
2 16
3 216
4 4096
5 100000
6 2985984
7 105413504
8 4294967296
9 198359290368
dtype: int64
Not really. 并不是的。 R and Python have pretty different philosophies when it comes to this kind of thing--in R it's possible to write a function which parses the entire syntax of its arguments before they are evaluated, whereas in Python it's not.
当涉及到这种事情时,R和Python有着截然不同的哲学 - 在R中,可以编写一个函数,在它们被评估之前解析其参数的整个语法,而在Python中它不是。 So in Python, this is impossible:
所以在Python中,这是不可能的:
df = pd.DataFrame({'a':[1,2],'b':[3,4],'c':[5,6],'d':[7,8]})
with(df, a + b + c)
However, this works: 但是,这有效:
sum(map(df.get, ('a','b','c'))) # gives Series([9,12])
If you wanted to apply other chained operations, you could implement support for something like this: 如果您想应用其他链式操作,可以实现以下类似的支持:
def chain(op, df, name, *names):
res = df[name]
while names:
res = op(res, df[names[0]])
names = names[1:]
return res
Then you can do this: 然后你可以这样做:
from operator import div
chain(div, df, 'a', 'b', 'c')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.