如何将查询列表传递给pandas数据帧,并输出结果列表?

时间:2016-10-12 00:06:20

标签: python python-3.x pandas dataframe

选择列值column_name等于标量some_value的行时,我们使用==:

df.loc[df['column_name'] == some_value]

或使用.query()

df.query('column_name == some_value')

在一个具体的例子中:

import pandas as pd
import numpy as np
df = pd.DataFrame({'Col1': 'what are men to rocks and mountains'.split(),
                   'Col2': 'the curves of your lips rewrite history.'.split(),
                   'Col3': np.arange(7),
                   'Col4': np.arange(7) * 8})

print(df)

         Col1      Col2  Col3  Col4
0       what       the     0     0
1        are    curves     1     8
2        men        of     2    16
3         to      your     3    24
4      rocks      lips     4    32
5        and   rewrite     5    40
6  mountains  history      6    48

查询可以是

rocks_row = df.loc[df['Col1'] == "rocks"]

输出

print(rocks_row)
    Col1  Col2  Col3  Col4
4  rocks  lips     4    32

我想通过一个值列表来查询数据帧,该数据帧输出一个"正确查询列表"。

要执行的查询将在列表中,例如

list_match = ['men', 'curves', 'history']

将输出满足此条件的所有行,即

matches = pd.concat([df1, df2, df3]) 

其中

df1 = df.loc[df['Col1'] == "men"]

df2 = df.loc[df['Col1'] == "curves"]

df3 = df.loc[df['Col1'] == "history"]

我的想法是创建一个接收

的函数
output = []
def find_queries(dataframe, column, value, output):
    for scalar in value: 
        query = dataframe.loc[dataframe[column] == scalar]]
        output.append(query)    # append all query results to a list
    return pd.concat(output)    # return concatenated list of dataframes

然而,这看起来特别慢,并没有实际利用熊猫数据结构。什么是"标准"通过pandas数据框传递查询列表的方法?

编辑:这是如何转化为更复杂的"在熊猫中查询?例如where有HDF5文件吗?

df.to_hdf('test.h5','df',mode='w',format='table',data_columns=['A','B'])

pd.read_hdf('test.h5','df')

pd.read_hdf('test.h5','df',where='A=["foo","bar"] & B=1')

2 个答案:

答案 0 :(得分:1)

处理此问题的最佳方法是使用布尔系列索引行,就像在R中一样。

以你的df为例,

In [5]: df.Col1 == "what"
Out[5]:
0     True
1    False
2    False
3    False
4    False
5    False
6    False
Name: Col1, dtype: bool

In [6]: df[df.Col1 == "what"]
Out[6]:
   Col1 Col2  Col3  Col4
0  what  the     0     0

现在我们将它与pandas isin功能结合起来。

In [8]: df[df.Col1.isin(["men","rocks","mountains"])]
Out[8]:
        Col1      Col2  Col3  Col4
2        men        of     2    16
4      rocks      lips     4    32
6  mountains  history.     6    48

要对多列进行过滤,我们可以将它们与&链接在一起和|像这样的运营商。

In [10]: df[df.Col1.isin(["men","rocks","mountains"]) | df.Col2.isin(["lips","your"])]
Out[10]:
        Col1      Col2  Col3  Col4
2        men        of     2    16
3         to      your     3    24
4      rocks      lips     4    32
6  mountains  history.     6    48

In [11]: df[df.Col1.isin(["men","rocks","mountains"]) & df.Col2.isin(["lips","your"])]
Out[11]:
    Col1  Col2  Col3  Col4
4  rocks  lips     4    32

答案 1 :(得分:1)

如果我正确理解了您的问题,您可以使用布尔索引作为@uhjish has already shown in his answer或使用query()方法:

$ line=$(sed '
    s/"/"Dcom.sun.management.jmxremote=true -Djava.rmi.server.hostname=x.x.x.x /
    s/authenticate/&=false/
' <<<"$line")
$ echo "$line"
KAFKA_JMX_OPTS="Dcom.sun.management.jmxremote=true -Djava.rmi.server.hostname=x.x.x.x -Dcom.sun.management.jmxremote.authenticate=false  -Dcom.sun.management.jmxremote.ssl=false "

In [30]: search_list = ['rocks','mountains'] In [31]: df Out[31]: Col1 Col2 Col3 Col4 0 what the 0 0 1 are curves 1 8 2 men of 2 16 3 to your 3 24 4 rocks lips 4 32 5 and rewrite 5 40 6 mountains history. 6 48 方法:

.query()

使用布尔索引:

In [32]: df.query('Col1 in @search_list and Col4 > 40')
Out[32]:
        Col1      Col2  Col3  Col4
6  mountains  history.     6    48

In [33]: df.query('Col1 in @search_list')
Out[33]:
        Col1      Col2  Col3  Col4
4      rocks      lips     4    32
6  mountains  history.     6    48

更新:使用功能:

In [34]: df.ix[df.Col1.isin(search_list) & (df.Col4 > 40)]
Out[34]:
        Col1      Col2  Col3  Col4
6  mountains  history.     6    48

In [35]: df.ix[df.Col1.isin(search_list)]
Out[35]:
        Col1      Col2  Col3  Col4
4      rocks      lips     4    32
6  mountains  history.     6    48

包括调试信息(打印查询):

def find_queries(df, qry, debug=0, **parms):
    if debug:
        print('[DEBUG]: Query:\t' + qry.format(**parms))
    return df.query(qry.format(**parms))

In [31]: find_queries(df, 'Col1 in {Col1} and Col4 > {Col4}', Col1='@search_list', Col4=40)
    ...:
Out[31]:
        Col1      Col2  Col3  Col4
6  mountains  history.     6    48

In [32]: find_queries(df, 'Col1 in {Col1} and Col4 > {Col4}', Col1='@search_list', Col4=10)
Out[32]:
        Col1      Col2  Col3  Col4
4      rocks      lips     4    32
6  mountains  history.     6    48