Pandas の DataFrame 列をリストに変換

Usama Imtiaz 2023年1月30日 2020年12月21日
  1. tolist() メソッドを使用して、DataFrame 列をリストに変換する
  2. list() 関数を使って DataFrame のカラムをリストに変換する
Pandas の DataFrame 列をリストに変換

このチュートリアル記事では、Pandas の tolist() メソッドを使用するなど、Pandas DataFrame カラムをリストに変換するためのさまざまな方法を紹介します。

tolist() メソッドを使用して、DataFrame 列をリストに変換する

Pandas の DataFrame 内のカラムは Pandas の Series です。ですから、列をリストに変換する必要がある場合は、Series の中の tolist() メソッドを使用することができます。tolist() メソッドは Pandas の DataFrame の Series をリストに変換します。

以下のコードでは、df['DOB'] は DataFrame から Series (列名を DOB とする) を返しています。

メソッドは 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() 関数を使って DataFrame のカラムをリストに変換する

また、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