Dev
python pandas 행(row) 삭제하는 여러가지 방법(예시코드 포함)
Dev Inventory
2023. 1. 23. 15:02
drop(): 이 방법을 사용하면 삭제할 행의 인덱스 레이블을 지정하여 DataFrame에서 행을 삭제할 수 있습니다.
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({'Name': ['John', 'Mike', 'Amy', 'Bob'], 'Age': [25, 30, 22, 35]})
# Delete the rows with index labels 0 and 2
df = df.drop([0, 2])
drop()함수와 조건식 함께 사용하는 방법 : 적절한 조건식을 전달하여 행 또는 열을 삭제할 수 있습니다.
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({'Name': ['John', 'Mike', 'Amy', 'Bob'], 'Age': [25, 30, 22, 35]})
# Delete the rows where the value of the 'Age' column is less than 25
df = df.drop(df[df['Age'] < 25].index, axis=0)
* drop() 메서드 를 사용할 때 원본 DataFrame의 행을 삭제하려면 매개변수(inplace=True)를 지정하는 것이 중요합니다 .
그렇지 않으면 행이 삭제된 데이터를 얻기 위해서는 반환된 데이터를 받아서 사용해야합니다.
조건식을 이용한 방법: 특정 조건을 충족하는 행을 삭제할 수도 있습니다.
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({'Name': ['John', 'Mike', 'Amy', 'Bob'], 'Age': [25, 30, 22, 35]})
# Delete the rows where the value of the 'Age' column is less than 25
df = df[df['Age'] >= 25]
query(): 이 방법을 사용하면 부울 표현식을 지정하여 DataFrame에서 행을 삭제할 수 있습니다.
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({'Name': ['John', 'Mike', 'Amy', 'Bob'], 'Age': [25, 30, 22, 35]})
# Delete the rows where the value of the 'Age' column is less than 25
df = df.query("Age >= 25")
del: 키워드를 사용하여 인덱스별로 행을 제거할 수 있습니다.
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({'Name': ['John', 'Mike', 'Amy', 'Bob'], 'Age': [25, 30, 22, 35]})
# Delete the rows with index labels 0 and 2
del df[0]
del df[2]