Skip to content
Minsing Log
Go back

English Edition

Pandas: How to Drop Rows that Contain a Specific Value without drop() method and for loop?

Programming & CS

How can I quickly remove rows containing a specific value without using a for loop?

drop() can become slower as the dataframe grows, so this is another method I found.

This method is called the boolean mask technique.

import pandas as pd

# 랜덤 데이터프레임 생성
df = pd.DataFrame({
   '무': [1, 2, 3, 4, 5],
   '야': [5, 15, 10, 20, 15],
   '호': [10, 15, 10, 20, 15],
   '테': [10, 15, 10, 20, 15],
   '스': [10, 15, 10, 20, 15]
})

# 삭제하려는 값들을 포함하는 리스트
values = [2, 4, 6, 8, 10]

# 리스트의 값들이 데이터프레임의 어떤 열에 있는지 확인
mask = df.isin(values)

# 리스트의 값들이 있는 행을 삭제
df = df[~mask.any(axis=1)]

print(df)

Brief Code Explanation

  1. Create a values list containing the values you want to delete.
  2. Use the df.isin() method to check whether each element of the df dataframe matches one of the values in the list. It returns True for matches and False otherwise, converting the result into a dataframe and storing it in the mask variable.

  1. Then, negate this mask to delete the rows containing the values in the list. To do this, use the ~ operator to invert the values in the mask. This makes the rows containing the values in the list False, while the other rows become True.

  2. Finally, use the any(axis=1) function to check whether at least one element is True for each row. This deletes the rows containing the values in the list.

Detailed Explanation 1

Useful Reference Site

공개 여정 구독

글이 올라오면 이메일로 보내드릴게요.

개발, 창업, 배움, 실패와 회고를 짧고 솔직하게 기록합니다. 검색으로 스쳐가는 독자가 아니라 여정을 따라오는 팬을 만들기 위한 뉴스레터입니다.

뉴스레터는 준비 중입니다. 그동안 RSS 로 구독하거나 이메일 로 알림을 요청해 주세요.


Share this post:

Comments

Sign in with GitHub to leave a comment.


Previous Post
RAGchain benchmark Mr.tydi
Next Post
MRR metric