【问题标题】:query using string in PyTables 3在 PyTables 3 中使用字符串进行查询
【发布时间】:2018-11-16 03:59:29
【问题描述】:

我有一张桌子:

h5file=open_file("ex.h5", "w")
class ex(IsDescription):
    A=StringCol(5, pos=0)
    B=StringCol(5, pos=1)
    C=StringCol(5, pos=2)
table=h5file.create_table('/', 'table', ex, "Passing string as column name")
table=h5file.root.table
rows=[
    ('abc', 'bcd', 'dse'),
    ('der', 'fre', 'swr'),
    ('xsd', 'weq', 'rty')
]
table.append(rows)
table.flush()

我正在尝试按以下方式查询:

find='swr'
creteria='B'
if creteria=='B':
    condition='B'
else:
    condition='C'
value=[x['A'] for x in table.where("""condition==find""")]
print(value)

返回:

ValueError:没有列参与条件condition==find

有没有办法在上面的查询中使用条件作为列名? 提前致谢。

【问题讨论】:

    标签: pytables


    【解决方案1】:

    是的,您可以使用 Pytables .where() 根据条件进行搜索。问题是您如何为table.where(condition) 构建查询。请参阅Pytables Users Guide 中 Table.where() 下有关字符串的注意事项:

    当查询条件包含字符串文字时,应特别注意。 ... Python 3 字符串是 unicode 对象。
    在 Python 3 中,“条件”应该这样定义:
    condition = 'col1 == b"AAAA"'
    原因是在 Python 3 中,“条件”意味着一个字节串(“col1”内容)和一个 unicode 文字(“AAAA”)之间的比较。

    您的查询的最简单形式如下所示。它返回符合条件的行的子集。注意对字符串和 unicode 使用单引号和双引号:

    query_table = table.where('C=="swr"') # search in column C
    

    我尽我所能重写了你的例子。见下文。它显示了几种输入条件的方法。我不够聪明,无法弄清楚如何将您的 creteriafind 变量组合成一个带有字符串和 unicode 字符的 condition 变量。

    from tables import *
    class ex(IsDescription):
        A=StringCol(5, pos=0)
        B=StringCol(5, pos=1)
        C=StringCol(5, pos=2)
    
    h5file=open_file("ex.h5", "w")
    
    table=h5file.create_table('/', 'table', ex, "Passing string as column name")
    ## table=h5file.root.table
    rows=[
        ('abc', 'bcd', 'dse'),
        ('der', 'fre', 'swr'),
        ('xsd', 'weq', 'rty')
    ]
    table.append(rows)
    table.flush()
    find='swr'
    query_table = table.where('C==find')
    for row in query_table :
      print (row)
      print (row['A'], row['B'], row['C'])
    
    value=[x['A'] for x in table.where('C == "swr"')]
    print(value)
    
    value=[x['A'] for x in table.where('C == find')]
    print(value)
    
    h5file.close() 
    

    输出如下图:

    /table.row (Row), pointing to row #1
    b'der' b'fre' b'swr'
    [b'der']
    [b'der']
    

    【讨论】:

      猜你喜欢
      • 2014-10-12
      • 2013-02-07
      • 1970-01-01
      • 1970-01-01
      • 2012-01-19
      • 2019-03-15
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多