簡體   English   中英

根據元組列表中的索引值從數據框中提取值

[英]Extracting values from a data frame based on index values in a list of tuples

在此處輸入圖片說明 我有一個數據框,我希望根據包含要提取的值的索引的元組列表從中提取值。 我也想提取相應的列和行標題。 關於如何做到這一點的任何想法。

這是一個例子:

數據框是顯示的圖像

元組列表:[(0,2),(1,0),(2,1)]

目的是使用第一個元組提取值40,並以元組的形式提取標題值(作業1,工人2)。 並對接下來的兩個元組執行相同的操作。

import pandas as pd
list_workers = ["Worker 1","worker 2","worker 3"]
list_jobs = ["Job 1","Job 2","Job 3"]
list_cost = [40,60,15,25,30,45,55,30,25]
indexes = [(0,2),(1,0),(2,1)]

#this section can be ignored: creates a matrix and adds it into a df
cost_arr = np.array(list_cost)
cost_mat = cost_arr.reshape(len(list_workers),len(list_jobs))
df = pd.concat([df,pd.DataFrame(cost_mat)],axis = 1)

#the image show is the resulting df
#to extract corresponding values from df for each tuple
for i in indexes:
    print (df.iat(i))

嘗試這個:

import pandas as pd
df = pd.DataFrame({'a' : [1, 2], 'b' : [3, 4]})
ls = [(0, 1), (1, 0)]
for i in ls:
    print(df.iloc[i[0], i[1]])

以下應該工作:

import pandas as pd
df=pd.DataFrame({'W1':[1,2],'W2':[3,4]},index=["J1","J2"])
tuples=[(0,1),(1,0)]
values=[]
fieldNames=[]
for t in tuples:
  values.append(df.iloc[t[0],t[1]])
  fieldNames.append((df.index[t[0]],df.columns[t[1]]))
print(values)
print(fieldNames)

您可以使用.iloc []方法進行基於索引的選擇。

如果您想遍歷所有項目;

for tuple in list_of_tuple:
    row, col = tuple[0], tuple[1]
    val = df.iloc[row, col]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM