如何使用元组数组查询pandas DataFrame?

Sam*_*mar 3 python indexing numpy dataframe pandas

我有一个pandas DataFrame具有以下结构:

样本数据帧图像

我有一系列元组

arr_tuples = [(0,3),(1,1),(1,3),(2,1)]

数组中的每个元组分别代表上述数据帧的行和列索引.

我可以在arr_tuplesfor循环中找到索引的数据框中的所有值,如下所示:

value_array = []
for item in arr_tuples:
    row = item[0]
    col = item[1]
    value = df.iloc[row,col] # I also tried df.get_value here with similar result 
    value_array.append(value)
Run Code Online (Sandbox Code Playgroud)

但这似乎是一种非常缓慢的方法.如果我的元组中有很多元组arr_tuples,则需要很长时间.

是否有更好,更快的方法来实现相同的目标?在pandas中有什么办法可以使用元组的列表/数组(包含行和列索引)来获取数据帧中的值吗?

piR*_*red 8

你可以使用pd.DataFrame.lookup一些zip和解压缩技巧

df.lookup(*zip(*arr_tuples))

array([ 4,  5,  7, 12])
Run Code Online (Sandbox Code Playgroud)