달나라 노트

Python Pandas : columns (DataFrame의 column 정보 불러오기.) 본문

Python/Python Pandas

Python Pandas : columns (DataFrame의 column 정보 불러오기.)

CosmosProject 2024. 6. 28. 19:01
728x90
반응형

 

 

 

Pandas의 columns는 DataFrame에 존재하는 Column의 정보를 출력해줍니다.

 

import pandas as pd

dict_test = {
    'col1': [1, 2, 3, 4, 5],
    'col2': [2, 3, 4, 5, 6],
}
df_test = pd.DataFrame(dict_test)
print(df_test)
print(df_test.columns)



-- Result
   col1  col2
0     1     2
1     2     3
2     3     4
3     4     5
4     5     6

Index(['col1', 'col2'], dtype='object')

 

 

 

 

list() method를 이용해서 column을 list의 형태로 만들 수도 있습니다.

 

import pandas as pd

dict_test = {
    'col1': [1, 2, 3, 4, 5],
    'col2': [2, 3, 4, 5, 6],
}
df_test = pd.DataFrame(dict_test)
print(df_test)
print(list(df_test.columns))



-- Result
   col1  col2
0     1     2
1     2     3
2     3     4
3     4     5
4     5     6

['col1', 'col2']

 

 

 

 

 

 

import pandas as pd

dict_test = {
    'col1': [1, 2, 3, 4, 5],
    'col2': [2, 3, 4, 5, 6],
}
df_test = pd.DataFrame(dict_test)
print(df_test)
print(df_test.columns)
print(df_test.columns.name)

df_test.columns.name = 'This is columns'
print(df_test)
print(df_test.columns)
print(df_test.columns.name)



-- Result
   col1  col2
0     1     2
1     2     3
2     3     4
3     4     5
4     5     6

Index(['col1', 'col2'], dtype='object')

None

This is columns  col1  col2
0                   1     2
1                   2     3
2                   3     4
3                   4     5
4                   5     6

Index(['col1', 'col2'], dtype='object', name='This is columns')

This is columns

 

 

- df_test.columns.name = 'This is columns'

또한 이런식으로 Column set의 이름을 조절할 수 있습니다.

 

column set의 이름은 기본적으로 None이며

이를 별도로 설정할 수 있습니다.

 

 

 

import pandas as pd

dict_test = {
    'col1': [1, 2, 3, 4, 5],
    'col2': [2, 3, 4, 5, 6],
}
df_test = pd.DataFrame(dict_test)
print(df_test)
print(df_test.columns)
print(df_test.columns.name)

df_test.columns.name = 'This is columns'
print(df_test)
print(df_test.columns)
print(df_test.columns.name)

df_test.columns.name = None
print(df_test)
print(df_test.columns)
print(df_test.columns.name)



-- Result
   col1  col2
0     1     2
1     2     3
2     3     4
3     4     5
4     5     6

Index(['col1', 'col2'], dtype='object')

None


This is columns  col1  col2
0                   1     2
1                   2     3
2                   3     4
3                   4     5
4                   5     6

Index(['col1', 'col2'], dtype='object', name='This is columns')

This is columns


   col1  col2
0     1     2
1     2     3
2     3     4
3     4     5
4     5     6

Index(['col1', 'col2'], dtype='object')

None

 

- df_test.columns.name = None

name을 없애고싶으면 위처럼 None을 할당하면 됩니다.

 

 

 

 

 

728x90
반응형
Comments