본문 바로가기
프로그램

[파이썬] pandas DataFrame의 인덱스 Header 위에 문자 추가

by 오디세이99 2023. 2. 3.
728x90
반응형

다음과 같이 임의의 DataFrame이 있습니다.

import pandas as pd
import random

df = pd.DataFrame(columns=range(4))
df.columns = ['month', '1949','1950','1951']

df.loc[len(df)] = ['January',112, 115, 145]
df.loc[len(df)] = ['Fabruary',118, 126, 150]
df.loc[len(df)] = ['March', 132, 141, 178]
df.loc[len(df)] = ['April', 129, 135, 163]
df = df.set_index('month')

인덱스 컬럼( month) 위에 year 라는 문자를 추가하려고 합니다.

 

다음과 같이 df.columns.name='year' 를 추가 합니다.

import pandas as pd
import random

df = pd.DataFrame(columns=range(4))
df.columns = ['month', '1949','1950','1951']
df.columns.name='year'                           # 인덱스 위에 year 추가

df.loc[len(df)] = ['January',112, 115, 145]
df.loc[len(df)] = ['Fabruary',118, 126, 150]
df.loc[len(df)] = ['March', 132, 141, 178]
df.loc[len(df)] = ['April', 129, 135, 163]
df = df.set_index('month')

728x90
반응형

댓글