FLa*_*Lab 5 python eval dataframe pandas
我在看pandas DataFrame eval方法(docs),它找到了一个不错的语法糖,也可以帮助提高性能。
这是来自文档的示例:
from numpy.random import randn
import pandas as pd
df = pd.DataFrame(randn(10, 2), columns=list('ab'))
df.eval('a + b')
Run Code Online (Sandbox Code Playgroud)
eval
如果列名中有空格,该如何使用?例:
df = pd.DataFrame(randn(10, 2), columns=["Col 1", "Col 2"])
Run Code Online (Sandbox Code Playgroud)
我尝试了这个:
df.eval('"Col 1" + "Col 2"')
Run Code Online (Sandbox Code Playgroud)
但这给出了错误:
TypeError: data type "Col 1" not understood
Run Code Online (Sandbox Code Playgroud)
pd.eval('df["Col 1"] + df["Col 2"]')
Run Code Online (Sandbox Code Playgroud)
这将 eval 的参数保留为字符串,但不如列名中没有空格的示例干净
例子:
print(df)
Col 1 Col 2
0 -0.206838 -1.007173
1 -0.762453 1.178220
2 -0.431943 -0.804775
3 0.830659 -0.244472
4 0.111637 0.943254
5 0.206615 0.436250
6 -0.568307 -0.680140
7 -0.127645 -0.098351
8 0.185413 -1.224999
9 0.767931 1.512654
print(pd.eval('df["Col 1"] + df["Col 2"]'))
0 -1.214011
1 0.415768
2 -1.236718
3 0.586188
4 1.054891
5 0.642865
6 -1.248447
7 -0.225995
8 -1.039586
9 2.280585
dtype: float64
Run Code Online (Sandbox Code Playgroud)
编辑
经过一番调查,如果您使用的是 python 引擎,上面的方法看起来在 python 2.7 或 3.6 中都有效:
pd.eval('df["Col 1"] + df["Col 2"]', engine='python')
Run Code Online (Sandbox Code Playgroud)
但是,这并没有为您numexpr
提供引擎可以提供的性能优势。在 python 2.7 中,此方法有效:
pd.eval('df["Col 1"] + df["Col 2"]', engine='numexpr')
Run Code Online (Sandbox Code Playgroud)
但是在 python 3.6 中你会得到错误ValueError: unknown type str160
。
我的猜测是,这是因为 Pandasnumexpr
在 3.6 中传递了一个 unicode 字符串,而在 2.7 中传递了一个字节串。我猜测,这个问题涉及到这个问题,也许这一次为好。
您可以使用以下方法执行此操作:
df.eval(df["Col 1"] + df["Col 2"])
Run Code Online (Sandbox Code Playgroud)
但这有点违背了 eval 函数的目的。
或者,您可以重命名列以使它们与 eval 语法兼容:
df.columns = df.columns.map(lambda x: x.replace(' ', '_'))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2464 次 |
最近记录: |