【问题标题】:Does pandas have equivalents to R's 'with()' and 'within()' functions?pandas 是否与 R 的“with()”和“with()”函数等效?
【发布时间】:2013-11-06 01:10:06
【问题描述】:

R 具有 with() 和 within() 函数,它们允许您引用 data.frame 的列,而无需在 data.frame 的名称前面添加。这对于避免一些击键和使语句更简单很有用。

熊猫中有类似的东西吗?

【问题讨论】:

    标签: python r pandas


    【解决方案1】:

    没有完全等价的东西(你不能像在 R 中那样将 DataFrame 附加到命名空间),但你可以使用实验性的 DataFrame.query() methodDataFrame.eval() method,在 0.13 中可用(候选版本应该在本周发布),会让你做这样的事情:

    >>> df = DataFrame({"A": range(10), "B": range(0, 20, 2)})
    >>> df
       A   B
    0  0   0
    1  1   2
    2  2   4
    3  3   6
    4  4   8
    5  5  10
    6  6  12
    7  7  14
    8  8  16
    9  9  18
    
    >>> df.query("A < 5 and B in (1, 2, 3, 5, 6)")
       A  B
    1  1  2
    3  3  6
    >>> df.eval("A + B")
    0     0
    1     3
    2     6
    3     9
    4    12
    5    15
    6    18
    7    21
    8    24
    9    27
    dtype: int64
    

    作为奖励,在大帧上,这可以通过 numexpr 加速。

    statsmodels' formula API 还允许您引用 R 中的公式。

    【讨论】:

    • 实际上与 withsubset 的性能比较也存在于仓库中的某个地方……不记得我把它放在哪里了。 subset -> DataFrame.query()with -> DataFrame.eval() 是我思考 pandas 方法与相应 R 版本之间关系的方式。
    • 因此,从技术上讲,DataFrame.eval() 是等价的,因为它采用任意表达式并在 DataFrame 实例的上下文中对其进行评估。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 2012-04-18
    • 1970-01-01
    • 2011-08-30
    • 2015-05-10
    • 1970-01-01
    • 2020-10-25
    相关资源
    最近更新 更多