將 Pandas DataFrame 列轉換為列表
Usama Imtiaz
2023年1月30日
2020年12月19日
![將 Pandas DataFrame 列轉換為列表](/img/Python%20Pandas/feature%20image%20-%20pandas%20column%20to%20list.png)
本教程文章將介紹不同的方法將 Pandas DataFrame 列轉換為列表,比如使用 Pandas 中的 tolist()
方法。
使用 tolist()
方法將 Dataframe 列轉換為列表
Pandas DataFrame 中的一列就是一個 Pandas Series
。因此,如果我們需要將一列轉換為一個列表,我們可以使用 Series
中的 tolist()
方法。
在下面的程式碼中,df['DOB']
從 DataFrame 中返回名稱為 DOB
的 Series
或列。
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()
函式將 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 列標題獲取為列表
- 如何刪除 Pandas DataFrame 列
- 如何在 Pandas 中將 DataFrame 列轉換為日期時間
- 如何獲得 Pandas 列中元素總和
- 如何更改 Panas DataFrame 列的順序
- 如何在 Pandas 中將 DataFrame 列轉換為字串