簡體   English   中英

如何從 Pandas 數據框中獲取特定行?

[英]How can I get specific row(s) from a pandas dataframe?

我正在嘗試通讀 pandas 文檔,但似乎無法找出解決問題的最佳方法。 我有一個名為 Awards 的 Pandas 數據框。

數據框的每一行代表一個獎項,每個獎項都有一個 ID。 我想從具有特定 ID 的數據框中提取獎勵,並使用其中的一些值進行比較。 請參閱下面的代碼片段。

我嘗試使用這個:

possible_awards = awards.loc[[awards['id'] ==  r_a['award_id']]]

但我不認為這是最好的方法。 一方面,我認為(?)它應該給我一個數組或另一個數據幀,而我真的知道只有一個獎項具有該 ID。 其次,我不知道如何遍歷返回的內容。

我希望能夠訪問此特定行的數據框列,如下所示:

if possible_award['institution_id'] == award['institution_id'] and possible_award['department'] == award['department']:

但是,當我遍歷“possible_awards”的任何對象時,我似乎無法做到這一點。 我收到以下錯誤:“字符串索引必須是整數”

def foo(researcher, award, researchers_and_awards, awards):
    for r_a in researchers_and_awards:
       if r_a['researcher_id'] == researcher['id']:
            possible_awards = awards.loc[[awards['id'] ==  r_a['award_id']]] 
        for index, possible_award in possible_awards:
            if possible_award['institution_id'] == award['institution_id'] and possible_award['department'] == award['department']:
                    return True
            if possible_award['institution_id'] != award['institution_id'] and possible_award['competition_year'] != award['competition_year']:
                return True
return False

我想找到一種干凈簡潔的方法來做到這一點。 任何幫助表示贊賞! 如果我需要進一步解釋,請告訴我。

你可以使用:

possible_awards = awards[awards['id']==r_a['award_id']]

然后像下面這樣迭代:

for idx,row in possible_awards.iterrows():
    # do whatever you want on this line with `row`

暫無
暫無

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

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