티스토리 뷰

반응형

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

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

 

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

Delete a column from a Pandas DataFrame

Pandas 데이터 프레임에서 열 삭제하기

 문제 내용 

To delete a column in a DataFrame, I can successfully use:

데이터 프레임에서 열을 삭제하려면 다음을 사용할 수 있습니다.
del df['column_name']

 

But why can't I use the following?

그런데 왜 다음을 사용할 수 없을까요?
del df.column_name

 

Since it is possible to access the column/Series as df.column_name, I expected this to work.

df.dlln_name으로 열/Series에 액세스할 수 있기 때문에 이 기능이 작동할 것으로 예상했습니다.

 

 

 

 높은 점수를 받은 Solution 

The best way to do this in Pandas is to use drop:

Pandas에서 이것을 하는 가장 좋은 방법은 드롭을 사용하는 것이다:
df = df.drop('column_name', axis=1)

 

where 1 is the axis number (0 for rows and 1 for columns.)

여기서 1은 축 번호입니다(행의 경우 0, 열의 경우 1).

 

To delete the column without having to reassign df you can do:

재할당하지 않고 열을 삭제하려면 다음을 수행할 수 있습니다.
df.drop('column_name', axis=1, inplace=True)

 

Finally, to drop by column number instead of by column label, try this to delete, e.g. the 1st, 2nd and 4th columns:

마지막으로 열 레이블 대신 열 번호별로 삭제하려면 아래를 시도하세요.(예를 들어 첫 번째, 두 번째 및 네 번째 열)
df = df.drop(df.columns[[0, 1, 3]], axis=1)  # df.columns is zero-based pd.Index

 

Also working with "text" syntax for the columns:

또한 열에 대해 "text" 구문으로 작업:
df.drop(['column_nameA', 'column_nameB'], axis=1, inplace=True)

 

Note: Introduced in v0.21.0 (October 27, 2017), the drop() method accepts index/columns keywords as an alternative to specifying the axis.

참고: v0.21.0(2017년 10월 27일)에 도입된 drop() 메서드는 축을 지정하는 대신 인덱스/열 키워드를 사용합니다.

 

So we can now just do:

이제 다음 작업을 수행할 수 있습니다.
df = df.drop(columns=['column_nameA', 'column_nameB'])

 

 

 가장 최근 달린 Solution 

Deleting a column using the iloc function of dataframe and slicing, when we have a typical column name with unwanted values:

원하지 않는 값을 가진 일반적인 열 이름이 있는 경우 데이터 프레임 및 슬라이스의 iloc 함수를 사용하여 열 삭제:
df = df.iloc[:,1:] # Removing an unnamed index column

 

Here 0 is the default row and 1 is the first column, hence :,1: is our parameter for deleting the first column.

여기서 0은 기본 행이고 1은 첫 번째 열이므로 :,1:은 첫 번째 열을 삭제하기 위한 매개 변수입니다.

 

 

 

출처 : https://stackoverflow.com/questions/13411544/delete-a-column-from-a-pandas-dataframe

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