티스토리 뷰

반응형

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

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

 

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

Sorting columns in pandas dataframe based on column name

판다스 데이터프레임에서 열 이름을 기반으로 열 정렬하기

 문제 내용 

I have a dataframe with over 200 columns. The issue is as they were generated the order is

200개 이상의 열이 있는 데이터프레임이 있습니다. 그러나 열이 생성된 순서대로 되어 있습니다.
['Q1.3','Q6.1','Q1.2','Q1.1',......]

 

I need to sort the columns as follows:

다음과 같이 열을 정렬해야합니다:
['Q1.1','Q1.2','Q1.3',.....'Q6.1',......]

 

Is there some way for me to do this within Python?

이것을 파이썬 내에서 수행할 수 있는 방법이 있을까요?

 

 

 

 높은 점수를 받은 Solution 

df = df.reindex(sorted(df.columns), axis=1)

This assumes that sorting the column names will give the order you want. If your column names won't sort lexicographically (e.g., if you want column Q10.3 to appear after Q9.1), you'll need to sort differently, but that has nothing to do with pandas.

이것은 열 이름을 정렬하면 원하는 순서를 얻을 수 있다는 가정입니다. 열 이름이 사전순으로 정렬되지 않는 경우 (예 : 열 Q10.3이 Q9.1 이후에 나타나야하는 경우) 다른 방식으로 정렬해야하지만 판다스와는 관련이 없습니다.

 

 

 

 가장 최근 달린 Solution 

For several columns, You can put columns order what you want:

여러 개의 열에 대해서, 다음과 같이 원하는 순서로 열을 정렬할 수 있습니다:
#['A', 'B', 'C'] <-this is your columns order
df = df[['C', 'B', 'A']]

 

This example shows sorting and slicing columns:

이 예제는 열을 정렬하고 슬라이싱하는 방법을 보여줍니다:
d = {'col1':[1, 2, 3], 'col2':[4, 5, 6], 'col3':[7, 8, 9], 'col4':[17, 18, 19]}
df = pandas.DataFrame(d)

 

You get:

아래와 같이 출력됩니다:
col1  col2  col3  col4
 1     4     7    17
 2     5     8    18
 3     6     9    19

 

Then do:

그런 다음 다음을 수행하면:
df = df[['col3', 'col2', 'col1']]

 

Resulting in:

결과는 다음과 같습니다:
col3  col2  col1
7     4     1
8     5     2
9     6     3     

 

 

출처 : https://stackoverflow.com/questions/11067027/sorting-columns-in-pandas-dataframe-based-on-column-name

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