pandas41 query-字符串表达式查询:大数据函数( tcy)

pandas41 query-字符串表达式查询:大数据函数( tcy)https://mp.csdn.net/postedit/85887334

pandas42 eval-字符串表达式查询:大数据( tcy)https://mp.csdn.net/postedit/85918442

query-字符串表达式查询 2019/1/6

1.函数:

df.query(expr,inplace = False,** kwargs )# 使用布尔表达式查询帧的列

参数:
# expr:str要评估的查询字符串。你可以在环境中引用变量,在它们前面添加一个'@'字符 。@a + b
# inplace=False:是否修改数据或返回副本
# kwargs:dict关键字参数

返回:DataFrame

注意:
# 默认修改Python语法'&'/'and'和'|'/'or'位运算符优先级高于布尔表达式,不同于Python
# 关键字参数parser='python'执行Python评估。
# engine='python' 用Python本身作为后端来传递评估表达式。不建议效率低。

# 默认实例df.index和 df.columns属性 DataFrame放在查询命名空间中,
# 这允许您将框架的索引和列视为框架中的列。标识符index用于帧索引; 
# 您还可以使用索引的名称在查询中标识它。
性能:
    # 涉及NumPy数组或Pandas DataFrames的复合表达式都会导致隐式创建临时数组
    # eval/query用在数据(df.values.nbytes>1万)性能提升明显;传统方法在小数组时运行得更快;
    # eval/query好处主要时节省内存,以及有时候简洁得语法
    # 可用指定不同解析器和引擎来运行这些查询;参见"Enhancing Performance" 。

实例1:

df = pd.DataFrame(np.arange(12).reshape(3, 4), columns=list('ABCD'))

  A B  C  D
0 0 1  2  3
1 4 5  6  7
2 8 9 10 11

# 实例1.1:python,numexpr 方式比较
result1 = df[(df.A < 8) & (df.B < 9)] #python方式
result2 = pd.eval('df[(df.A < 8) & (df.B < 9)]')#numexpr 方式

np.allclose(result1, result2) # True

# 实例1.2:eval,query,比较
# 相同点:计算表达式结果
# 不同点:eval若表达式为逻辑,结果返回bool数组;query则返回bool数组的数据

import numexpr

result3= df[df.eval('A<8 & B<9')]
result4 = df.query('A < 8 and B < 9')
result3.equals(result4)                        #True 结果result1==result2==result3==result4

a=df.A;b=df.B
result5= df[numexpr.evaluate('(a<8) &(b < 9)')]#等效;表达式不能含df.A

实例2:

# 实例2:@符合来标记本地变量
Cmean = df['C'].mean() #6.0
result1 = df[(df.A < Cmean) & (df.B < Cmean)]
result1 = df.query('A < @Cmean and B < @Cmean')#等价
result1

  A B C D
0 0 1 2 3
1 4 5 6 7

实例3:多索引

# 实例3.1:列名
df.query('(A < B) & (B < C)') #numexpr 方式 A,B,C为列名

# 实例3.2:单索引名+列名
df.query('a < B and B < C')   #a为单索引名,B,C为列名
df.query('index < B < C')     #index为单索引(非索引名),B,C为列名

# 实例3.3:单索引名a与列名a相同
df.query('a > 2')             # 用列'a',单索引名a与列名a相同列名称优先
df.query('index > 2')         #index为单索引(非索引名),单索引名a与列名a相同列名称优先

# 实例3.4:列名为index- 应该考虑将列重命名
df.query('ilevel_0 > 2')      #ilevel_0为单索引(非索引名)

实例4:多索引MultiIndex

colors = np.random.choice(['red', 'blue'], size=6)
foods = np.random.choice(['eggs', 'meat'], size=6)
index = pd.MultiIndex.from_arrays([colors, foods], names=['color', 'food'])
df = pd.DataFrame(np.arange(12).reshape(6, 2), index=index)
df

            0  1
color food
blue meat   0  1
     eggs   2  3
     meat   4  5
red  meat   6  7
blue meat   8  9
     eggs   10 11

# 实:4.1:索引名
df.query('color == "red"')

# 实例4.2:索引无名称
df.index.names = [None, None]
df.query('ilevel_0 == "red"') #ilevel_0第0级的索引级别
df.query('ilevel_1 == "meat"')#ilevel_1第1级的索引级别

实例5:

#实例5:多数据df - 具有相同列名(或索引级别/名称)

df1 = pd.DataFrame(np.arange(12).reshape(4,3), columns=list('abc'))+10
df2=df1+10

expr = '19 <= a <= c <= 22'
result=list(map(lambda frame: frame.query(expr), [df1, df2]))

# df1      df2        result
   a  b  c    a  b  c [ a b c
0 10 11 12 0 20 21 22 3 19 20 21,
1 13 14 15 1 23 24 25 a b c
2 16 17 18 2 26 27 28 0 20 21 22]
3 19 20 21 3 29 30 31 

实例6:

# 实例6:Python与pandas语法比较
# 完全类似numpy的语法

# 实例6.1:比较运算符,逻辑运算符
df = pd.DataFrame(np.random.randint(10, size=(10, 3)), columns=list('ABC'))

df.query('(A< B) & (B< C)')
df[(df.A < df.B) & (df.B < df.C)]
df.query('A< B & B < C')
df.query('A< B and B < C')
df.query('A < B < C') #全部等价

============================================================
# 实例6.2:==操作符与list对象的特殊用法
# ==/ !=工程,以类似in/not in

df.query('b == ["a", "b", "c"]')==df[df.b.isin(["a", "b", "c"])]

df.query('c == [1, 2]')
df.query('c != [1, 2]')

# using in/not in
df.query('[1, 2] in c')
df.query('[1, 2] not in c')
df[df.c.isin([1, 2])]# pure Python
============================================================
# 实例6.3:in与not in
df = pd.DataFrame({'a': list('abcdef'), 'b': list('fedfed'),'c': 5, 'd':5})

  a b c d
0 a f 5 5
1 b e 5 5
2 c d 5 5
3 d f 5 5
4 e e 5 5
5 f d 5 5

df.query('a in b and c < d') #与其他表达式结合获得非常简洁查询
df[df.b.isin(df.a) & (df.c < df.d)]

result1=df[df.a.isin(df.b)]
result2=df.query('a not in b')
result3=df[~df.a.isin(df.b)] # pure Python

# result1   result2      result3
  a b c d     a b c d      a b c d
3 d f 5 5   0 a f 5 5    0 a f 5 5
4 e e 5 5   1 b e 5 5    1 b e 5 5
5 f d 5 5   2 c d 5 5    2 c d 5 5

============================================================
# 实例6.4:布尔运算符not或~运算符否定布尔表达式

df = pd.DataFrame(np.arange(9).reshape(3,3), columns=list('ABC'))
df['bools'] = df.eval('C>=5')

result1=df.query('not bools')
result2=(df.query('not bools') == df[~df.bools])

# df            result1           result2
  A B C bools     A B C bools        A    B     C bools
0 0 1 2 False   0 0 1 2 False    0 True True True True
1 3 4 5 True 
2 6 7 8 True 

# 复杂表达式:
df.query('A < B< C and (not bools) or bools > 2')               #短查询语法
df[(df.A < df.B) & (df.B < df.C) & (~df.bools) | (df.bools > 2)]#等效于纯Python

猜你喜欢

转载自blog.csdn.net/tcy23456/article/details/85887334