개발/파이썬

Pandas에서 열 이름 바꾸기

맨날치킨 2022. 12. 1. 08:05
반응형

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

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

 

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

Renaming column names in Pandas

Pandas에서 열 이름 바꾸기

 문제 내용 

I want to change the column labels of a Pandas DataFrame from

Pandas 데이터 프레임의 열 레이블을 다음에서 변경합니다.
['$a', '$b', '$c', '$d', '$e']

 

to

아래로..
['a', 'b', 'c', 'd', 'e']

 

 

 높은 점수를 받은 Solution 

Rename Specific Columns

특정 열 이름 바꾸기

 

Use the df.rename() function and refer the columns to be renamed. Not all the columns have to be renamed:

df.rename() 함수를 사용하고 이름을 변경할 열을 참조하십시오. 모든 열의 이름을 변경할 필요는 없습니다.
df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})
# Or rename the existing DataFrame (rather than creating a copy) 
df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)

 

Minimal Code Example

최소 코드 예제
df = pd.DataFrame('x', index=range(3), columns=list('abcde'))
df

   a  b  c  d  e
0  x  x  x  x  x
1  x  x  x  x  x
2  x  x  x  x  x

 

The following methods all work and produce the same output:

다음 방법은 모두 작동하며 동일한 출력을 생성합니다.
df2 = df.rename({'a': 'X', 'b': 'Y'}, axis=1)  # new method
df2 = df.rename({'a': 'X', 'b': 'Y'}, axis='columns')
df2 = df.rename(columns={'a': 'X', 'b': 'Y'})  # old method  

df2

   X  Y  c  d  e
0  x  x  x  x  x
1  x  x  x  x  x
2  x  x  x  x  x

 

Remember to assign the result back, as the modification is not-inplace. Alternatively, specify inplace=True:

수정 사항이 적용되지 않으므로 결과를 다시 할당해야 합니다. 또는 inplace=True를 지정합니다:
df.rename({'a': 'X', 'b': 'Y'}, axis=1, inplace=True)
df

   X  Y  c  d  e
0  x  x  x  x  x
1  x  x  x  x  x
2  x  x  x  x  x
 

 

From v0.25, you can also specify errors='raise' to raise errors if an invalid column-to-rename is specified. See v0.25 rename() docs.

v0.25부터는 잘못된 열 대 변수가 지정된 경우 오류를 발생시키기 위해 errors='message'를 지정할 수도 있습니다. v0.25 rename() 문서를 참조하십시오.

 


Reassign Column Headers

열 머리글 재할당

 

Use df.set_axis() with axis=1 and inplace=False (to return a copy).

df.set_axis를 축=1, inplace=False(복사본을 반환하려면)와 함께 사용합니다.
df2 = df.set_axis(['V', 'W', 'X', 'Y', 'Z'], axis=1, inplace=False)
df2

   V  W  X  Y  Z
0  x  x  x  x  x
1  x  x  x  x  x
2  x  x  x  x  x

 

This returns a copy, but you can modify the DataFrame in-place by setting inplace=True (this is the default behaviour for versions <=0.24 but is likely to change in the future).

사본을 반환하지만 inplace=True를 설정하여 DataFrame을 수정할 수 있습니다.(이것은 버전 <=0.24의 기본 동작이지만 향후 변경될 가능성이 있습니다).

 

You can also assign headers directly:

헤더를 직접 할당할 수도 있습니다.

 

df.columns = ['V', 'W', 'X', 'Y', 'Z']
df

   V  W  X  Y  Z
0  x  x  x  x  x
1  x  x  x  x  x
2  x  x  x  x  x

 

 

 가장 최근 달린 Solution 

# This way it will work
import pandas as pd

# Define a dictionary 
rankings = {'test': ['a'],
        'odi': ['E'],
        't20': ['P']}

# Convert the dictionary into DataFrame
rankings_pd = pd.DataFrame(rankings)

# Before renaming the columns
print(rankings_pd)

rankings_pd.rename(columns = {'test':'TEST'}, inplace = True)

 

 

출처 : https://stackoverflow.com/questions/11346283/renaming-column-names-in-pandas

반응형