티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Use a list of values to select rows from a Pandas dataframe
값 리스트를 사용하여 Panda 데이터 프레임에서 행 선택
문제 내용
Let’s say I have the following Pandas dataframe:
다음과 같은 Pandas 데이터 프레임이 있다고 가정해 보겠습니다.
df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]})
df
A B
0 5 1
1 6 2
2 3 3
3 4 5
I can subset based on a specific value:
특정 값을 기준으로 부분 집합을 지정할 수 있습니다.
x = df[df['A'] == 3]
x
A B
2 3 3
But how can I subset based on a list of values? - something like this:
하지만 어떻게 하면 값 리스트를 기반으로 부분 집합을 만들 수 있을까요? - 다음과 같습니다.
list_of_values = [3,6]
y = df[df['A'] in list_of_values]
To get:
받는 방법:
A B
1 6 2
2 3 3
높은 점수를 받은 Solution
You can use the isin
method:
isin 메서드를 사용할 수 있습니다.
In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3
And to get the opposite use ~
:
반대로 사용하려면 ~:
In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5
가장 최근 달린 Solution
list_of_values
doesn't have to be a list
; it can be set
, tuple
, dictionary
, numpy array, pandas Series, generator, range
etc. and isin()
and query()
will still work.
list_of_values는 리스트일 필요가 없으며, 세트, 튜플, 딕셔너리, numpy array, pandas 시리즈, 제너레이터, range 등이 가능하며, isIn()및 query()는 여전히 작동합니다.
Some common problems with selecting rows
행 선택과 관련된 몇 가지 일반적인 문제
1. list_of_values
is a range
1. list_of_values는 범위입니다.
If you need to filter within a range, you can use between()
method or query()
.
범위 내에서 필터링해야 하는 경우 between() 메서드 또는 query()를 사용할 수 있습니다.
list_of_values = [3, 4, 5, 6] # a range of values
df[df['A'].between(3, 6)] # or
df.query('3<=A<=6')
2. Return df
in the order of list_of_values
2. list_of_values 순으로 df를 반환합니다.
In the OP, the values in list_of_values
don't appear in that order in df
. If you want df
to return in the order they appear in list_of_values
, i.e. "sort" by list_of_values
, use loc
.
OP에서 list_of_values의 값은 df의 해당 순서로 나타나지 않습니다. df가 list_of_values에 나타나는 순서, 즉 list_of_values별로 "sort"를 반환하려면 loc를 사용합니다.
list_of_values = [3, 6]
df.set_index('A').loc[list_of_values].reset_index()
If you want to retain the old index, you can use the following.
이전 인덱스를 유지하려면 다음을 사용할 수 있습니다.
list_of_values = [3, 6, 3]
df.reset_index().set_index('A').loc[list_of_values].reset_index().set_index('index').rename_axis(None)
3. Don't use apply
3. apply를 사용하지 마십시오.
In general, isin()
and query()
are the best methods for this task; there's no need for apply()
. For example, for function f(A) = 2*A - 5
on column A
, both isin()
and query()
work much more efficiently:
일반적으로 isin() 및 query()는 이 작업에 가장 적합한 메서드입니다. apply()가 필요 없습니다. 예를 들어 A 열의 f(A) = 2*A - 5 함수의 경우 isin() 및 query()가 훨씬 더 효율적으로 작동합니다.
df[(2*df['A']-5).isin(list_of_values)] # or
df[df['A'].mul(2).sub(5).isin(list_of_values)] # or
df.query("A.mul(2).sub(5) in @list_of_values")
4. Select rows not in list_of_values
4. list_of_values에 없는 행을 선택
To select rows not in list_of_values
, negate isin()
/in
:
list_of_values에 없는 행을 선택하려면 isin()/in의 부정을 사용하세요:
df[~df['A'].isin(list_of_values)]
df.query("A not in @list_of_values") # df.query("A != @list_of_values")
5. Select rows where multiple columns are in list_of_values
5. 여러 열이 list_of_values에 있는 행을 선택합니다.
If you want to filter using both (or multiple) columns, there's any()
and all()
to reduce columns (axis=1
) depending on the need.
두 열(또는 여러 열)을 사용하여 필터링하려는 경우 필요에 따라 열(축=1)을 줄이기 위한 any() 및 all()이 있습니다.
- Select rows where at least one of
A
orB
is inlist_of_values
:df[df[['A','B']].isin(list_of_values).any(1)] df.query("A in @list_of_values or B in @list_of_values")
- Select rows where both of
A
andB
are inlist_of_values
:df[df[['A','B']].isin(list_of_values).all(1)] df.query("A in @list_of_values and B in @list_of_values")
A 또는 B 중 하나 이상이 list_of_values에 있는 행 선택:
A와 B가 모두 list_of_values에 있는 행 선택:
Bonus:
보너스:
You can also call isin()
inside query()
:
query() 내부의 isin()을 호출할 수도 있습니다.
df.query("A.isin(@list_of_values).values")
출처 : https://stackoverflow.com/questions/12096252/use-a-list-of-values-to-select-rows-from-a-pandas-dataframe
'개발 > 파이썬' 카테고리의 다른 글
Dictionary 형태의 문자열 표현을 Dictionary로 변환하기 (0) | 2022.12.10 |
---|---|
파이썬에서 Dictionary 키를 리스트로 가져오기 (0) | 2022.12.10 |
Python 디렉토리에 있는 모든 목록 가져오기 (0) | 2022.12.09 |
파이썬에서 파일 크기 가져오기 (0) | 2022.12.09 |
딕셔너리에서 값이 최대인 키 가져오기 (0) | 2022.12.08 |