Pandas DataFrame 열을 목록으로 변환

Usama Imtiaz 2023년1월30일 2020년12월25일
  1. tolist()메서드를 사용하여 데이터 프레임 열을 목록으로 변환
  2. list()함수를 사용하여 데이터 프레임 열을 목록으로 변환
Pandas DataFrame 열을 목록으로 변환

이 튜토리얼 기사에서는 Pandas에서tolist()메서드를 사용하는 것과 같이 Pandas DataFrame 열을 목록으로 변환하는 다양한 방법을 소개합니다.

tolist()메서드를 사용하여 데이터 프레임 열을 목록으로 변환

Pandas 데이터 프레임의 열은 Pandas Series입니다. 따라서 열을 목록으로 변환해야하는 경우Series에서tolist()메서드를 사용할 수 있습니다. tolist()는 pandas 데이터 프레임의Series를 목록으로 변환합니다.

아래 코드에서df['DOB']는 DataFrame에서 이름이DOBSeries 또는 열을 반환합니다.

tolist()메소드는Series를 목록으로 변환합니다.

import pandas as pd

df=pd.DataFrame([
        ['James',   '1/1/2014',    '1000'],
        ['Michelina',   '2/1/2014',    '12000'],
        ['Marc',   '3/1/2014',    '36000'],
        ['Bob',   '4/1/2014',    '15000'],
        ['Halena',   '4/1/2014',    '12000']
        ], columns=['Name', 'DOB','Salary'])

print("Pandas DataFrame:\n\n",df,"\n")

list_of_single_column = df['DOB'].tolist()

print("the list of a single column from the dataframe\n",
        list_of_single_column,
        "\n",
        type(list_of_single_column))

출력:

Pandas DataFrame:

         Name       DOB Salary
0      James  1/1/2014   1000
1  Michelina  2/1/2014  12000
2       Marc  3/1/2014  36000
3        Bob  4/1/2014  15000
4     Halena  4/1/2014  12000 

the list of a single column from the dataframe
 ['1/1/2014', '2/1/2014', '3/1/2014', '4/1/2014', '4/1/2014'] 
 <class 'list'>

list()함수를 사용하여 데이터 프레임 열을 목록으로 변환

또한list()함수를 사용하여 DataFrame을list()함수에 전달하여 DataFrame 열을 목록으로 변환 할 수 있습니다.

이 접근 방식을 보여주기 위해 위와 동일한 데이터를 사용합니다.

import pandas as pd

df=pd.DataFrame([
        ['James',   '1/1/2014',    '1000'],
        ['Michelina',   '2/1/2014',    '12000'],
        ['Marc',   '3/1/2014',    '36000'],
        ['Bob',   '4/1/2014',    '15000'],
        ['Halena',   '4/1/2014',    '12000']
        ], columns=['Name', 'DOB','Salary'])

print("Pandas DataFrame:\n\n",df,"\n")

list_of_single_column = list(df['DOB'])

print("the list of a single column from the dataframe\n",
        list_of_single_column,
        "\n",
        type(list_of_single_column))

출력:

Pandas DataFrame:

         Name       DOB Salary
0      James  1/1/2014   1000
1  Michelina  2/1/2014  12000
2       Marc  3/1/2014  36000
3        Bob  4/1/2014  15000
4     Halena  4/1/2014  12000 

the list of a single column from the dataframe
 ['1/1/2014', '2/1/2014', '3/1/2014', '4/1/2014', '4/1/2014'] 
 <class 'list'>

관련 문장 - Pandas DataFrame Column

관련 문장 - Pandas DataFrame