티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to iterate over rows in a DataFrame in Pandas

Pandas에서 데이터 프레임의 행을 반복하는 방법

 문제 내용 

I have a pandas dataframe, df:

pandas 데이터 프레임이 있습니다. df:

 

   c1   c2
0  10  100
1  11  110
2  12  120

How do I iterate over the rows of this dataframe? For every row, I want to be able to access its elements (values in cells) by the name of the columns. For example:

이 데이터 프레임의 행을 어떻게 반복합니까? 모든 행에 대해 열 이름으로 해당 요소(셀의 값)에 액세스할 수 있어야 합니다. 예:

 

for row in df.rows:
    print(row['c1'], row['c2'])

I found a similar question which suggests using either of these:

다음 중 하나를 사용할 것을 제안하는 유사한 질문을 찾았습니다.

 

for date, row in df.T.iteritems():
for row in df.iterrows():

But I do not understand what the row object is and how I can work with it.

하지만 나는 그 행 객체가 무엇이고 내가 어떻게 그것으로 작업할 수 있는지 이해할 수 없다.

 

 

 

 높은 점수를 받은 Solution 

DataFrame.iterrows is a generator which yields both the index and row (as a Series):

DataFrame.iterrows는 인덱스와 행을 모두 직렬로 생성하는 생성기입니다.

 

import pandas as pd

df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})
df = df.reset_index()  # make sure indexes pair with number of rows

for index, row in df.iterrows():
    print(row['c1'], row['c2'])
10 100
11 110
12 120

 

 

 가장 최근 달린 Solution 

Disclaimer: Although here are so many answers which recommend not using an iterative (loop) approach (and I mostly agree), I would still see it as a reasonable approach for the following situation:

고지 사항: 비록 여기 반복적인 (루프) 접근법을 사용하지 말 것을 권고하는 많은 답변이 있지만(그리고 나는 대부분 동의한다), 나는 여전히 그것을 다음 상황에 대한 합리적인 접근법으로 볼 것이다.

 

Extend a dataframe with data from an API

API의 데이터로 데이터 프레임 확장

 

Let's say you have a large dataframe which contains incomplete user data. Now you have to extend this data with additional columns, for example, the user's age and gender.

불완전한 사용자 데이터를 포함하는 큰 데이터 프레임이 있다고 가정해 보겠습니다. 이제 이 데이터를 사용자의 연령 및 성별과 같은 추가 열로 확장해야 합니다.

 

Both values have to be fetched from a backend API. I'm assuming the API doesn't provide a "batch" endpoint (which would accept multiple user IDs at once). Otherwise, you should rather call the API only once.

두 값 모두 백엔드 API에서 가져와야 합니다. 나는 API가 (한 번에 여러 사용자 ID를 허용하는) "배치" 엔드포인트를 제공하지 않는다고 가정한다. 그렇지 않으면 API를 한 번만 호출해야 합니다.

 

The costs (waiting time) for the network request surpass the iteration of the dataframe by far. We're talking about network round trip times of hundreds of milliseconds compared to the negligibly small gains in using alternative approaches to iterations.

네트워크 요청에 대한 비용(대기 시간)은 데이터 프레임의 반복을 훨씬 능가합니다. 우리는 반복에 대한 대안적 접근법을 사용하는 데 있어 무시할 수 없을 정도로 작은 이득과 비교하여 수백 밀리초의 네트워크 왕복 시간에 대해 이야기하고 있다.

 

One expensive network request for each row

각 행에 대해 하나의 값비싼 네트워크 요청

 

So in this case, I would absolutely prefer using an iterative approach. Although the network request is expensive, it is guaranteed being triggered only once for each row in the dataframe. Here is an example using DataFrame.iterrows:

그래서 이 경우에는, 저는 반복적인 접근법을 사용하는 것을 절대적으로 선호합니다. 네트워크 요청은 비용이 많이 들지만 데이터 프레임의 각 행에 대해 한 번만 트리거되도록 보장됩니다. 다음은 DataFrame.iterrows를 사용하는 예입니다.

 

Example

 

for index, row in users_df.iterrows():
  user_id = row['user_id']

  # Trigger expensive network request once for each row
  response_dict = backend_api.get(f'/api/user-data/{user_id}')

  # Extend dataframe with multiple data from response
  users_df.at[index, 'age'] = response_dict.get('age')
  users_df.at[index, 'gender'] = response_dict.get('gender')

 

 

출처 : https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas

반응형
댓글
공지사항
최근에 올라온 글