使用列表从pandas DataFrame中选择行

时间:2015-03-04 18:45:02

标签: python pandas

我有一份清单如下

[[1, 2], [1, 3]]

DataFrame类似于

  A B C
0 1 2 4
1 0 1 2
2 1 3 0

我想要一个DataFrame,如果A列中的值等于任何嵌套列表的第一个元素,并且相应行的B列中的值等于同一嵌套列表的第二个元素。< / p>

因此生成的DataFrame应该是

  A B C
0 1 2 4
2 1 3 0

2 个答案:

答案 0 :(得分:0)

以下代码确实需要:

tmp_filter = pandas.DataFrame(None) #The dataframe you want
# Create your list and your dataframe
tmp_list = [[1, 2], [1, 3]]
tmp_df = pandas.DataFrame([[1,2,4],[0,1,2],[1,3,0]], columns = ['A','B','C'])

#This function will pass the df pass columns by columns and
#only keep the columns with the value you want
def pass_true_df(df, cond):
    for i, c in enumerate(cond):
        df = df[df.iloc[:,i] == c]
    return df

# Pass through your list and add the row you want to keep
for i in tmp_list:
    tmp_filter = pandas.concat([tmp_filter, pass_true_df(tmp_df, i)])

答案 1 :(得分:0)

import pandas
df = pandas.DataFrame([[1,2,4],[0,1,2],[1,3,0],[0,2,5],[1,4,0]],
                      columns = ['A','B','C'])
filt = pandas.DataFrame([[1, 2], [1, 3],[0,2]],
                          columns = ['A','B'])

accum = []

#grouped to-filter
data_g = df.groupby('A')
for k2,v2 in data_g:
    accum.append(v2[v2.B.isin(filt.B[filt.A==k2])])

print(pandas.concat(accum))

结果:

   A  B  C
3  0  2  5
0  1  2  4
2  1  3  0

(我将数据和过滤器作为测试进行了一些复杂的处理。)