Pandas DataFrame 열의 순서를 변경하는 방법

  1. Pandas에서 새로 원하는 순서대로 열을 나열하십시오
  2. Pandas의 특정 위치에 새 열 삽입
  3. Pandas에서 주어진 순서에 대한reindex
Pandas DataFrame 열의 순서를 변경하는 방법

우리는insertreindex를 사용하여 원하는 순서대로 열 이름을 할당하는 것과 같은 다른 방법으로 DataFrame열의 순서를 변경하는 방법을 소개 할 것입니다.

Pandas에서 새로 원하는 순서대로 열을 나열하십시오

가장 간단한 방법은columns 목록으로DataFrame을 다시 할당하거나 원하는 순서대로 열 이름을 지정하는 것입니다.

# python 3.x import pandas as pd  df = pd.DataFrame(  {  "a": ["1", "2", "3", "4"],  "b": [16, 7, 6, 16],  "c": [61, 57, 16, 36],  "d": ["12", "22", "13", "44"],  "e": ["Green", "Red", "Blue", "Yellow"],  "f": [1, 11, 23, 66],  } ) print(df) df = df[["e", "c", "b", "f", "d", "a"]] print("Rearranging ..................") print("..............................") print(df) 

출력:

 a b c d e f 0 1 16 61 12 Green 1 1 2 7 57 22 Red 11 2 3 6 16 13 Blue 23 3 4 16 36 44 Yellow 66 Rearranging .................. ..............................  e c b f d a 0 Green 61 16 1 12 1 1 Red 57 7 11 22 2 2 Blue 16 6 23 13 3 3 Yellow 36 16 66 44 4 

Pandas의 특정 위치에 새 열 삽입

새 열을 만드는 경우 원하는 위치에 열을 삽입 할 수 있습니다.

# python 3.x import pandas as pd  df = pd.DataFrame(  {  "a": ["1", "2", "3", "4"],  "b": [16, 7, 6, 16],  "c": [61, 57, 16, 36],  "d": ["12", "22", "13", "44"],  "e": ["Green", "Red", "Blue", "Yellow"],  "f": [1, 11, 23, 66],  } ) print(df) print("Inserting ..................") print("..............................") df.insert(0, "newColMean", df.mean(1)) print(df) 

출력:

 newColMean a b c d e f 0 26.000000 1 16 61 12 Green 1 1 25.000000 2 7 57 22 Red 11 2 15.000000 3 6 16 13 Blue 23 3 39.333333 4 16 36 44 Yellow 66 

Pandas에서 주어진 순서에 대한reindex

reindex는 아마도 컬럼을 재정렬하는 가장 효율적인 방법입니다.

# python 3.x import pandas as pd  df = pd.DataFrame(  {  "a": ["1", "2", "3", "4"],  "b": [16, 7, 6, 16],  "c": [61, 57, 16, 36],  "d": ["12", "22", "13", "44"],  "e": ["Green", "Red", "Blue", "Yellow"],  "f": [1, 11, 23, 66],  } ) print(df) print("Rearranging ..................") print("..............................") df = df.reindex(columns=["a", "f", "d", "b", "c", "e"]) print(df) 

출력:

 a b c d e f 0 1 16 61 12 Green 1 1 2 7 57 22 Red 11 2 3 6 16 13 Blue 23 3 4 16 36 44 Yellow 66 Rearranging .................. ..............................  a f d b c e 0 1 1 12 16 61 Green 1 2 11 22 7 57 Red 2 3 23 13 6 16 Blue 3 4 66 44 16 36 Yellow 
튜토리얼이 마음에 드시나요? DelftStack을 구독하세요 YouTube에서 저희가 더 많은 고품질 비디오 가이드를 제작할 수 있도록 지원해주세요. 구독하다

관련 문장 - Pandas DataFrame

관련 문장 - Pandas DataFrame Column