獲取 Pandas DataFrame 中特定列的值列表


Pandas 是一個 Python 庫,用於探索和清理雜亂的資料集,並使資料適合於提取必要的和有價值的見解。Pandas 中的 DataFrame 是一種二維資料結構,非常類似於電子表格、SQL 表格和 Excel 資料表。

我們可以使用多種方法來提取特定的列值。

  • 使用 '.values.tolist()' 方法

  • 使用 '.loc[]' 方法

  • 使用 '.iloc[]' 方法

  • 使用 'get()' 函式

方法 1:使用 .values.tolist() 方法

'.values' 用於從 Python 字典中提取與某個鍵相關聯的所有值,作為普通列表或陣列。

'.tolist()' 用於將此類普通列表或 NumPy 陣列轉換為“Python 列表”。

語法

col_vals=df['col_name'].values.tolist()

示例

建立一個包含學生姓名、年齡和最喜歡的學科的表格,並使用 tolist() 方法提取“最喜歡的學科”列的值。

演算法

  • 首先匯入所需的庫。

  • 根據要求建立一個表格。

  • 現在將表格作為變數 df 轉換為 DataFrame 物件。

  • 對 DataFrame df 應用屬性 '.values'。

  • 獲得的輸出將是一個 NumPy 陣列,現在要將其轉換為列表,應用 '.tolist()' 方法,因為我們的需求是列表。

  • 最後,使用內建的 'print()' 函式列印輸出。

import pandas as pd
import numpy as np
#creating a table

student_data={
   'Name of the Student': ['Alice', 'Cassie', 'Henry', 'Steven'],
   'Age':[15,13,16,14],
   'Favourite Subject':['Math', 'Social', 'Science', 'English']
}

#Now, we will turn the student_data table into Dataframe.
print("DataFrame that we created:")
df=pd.DataFrame(student_data)
print(df)

#tolist() is used to convert the column values into a list.
print("Extracted values of desired Column:")
col_vals=df['Favourite Subject'].values.tolist()
print(col_vals)

輸出

DataFrame that we created:
  Name of the Student  Age Favourite Subject
0               Alice   15              Math
1              Cassie   13            Social
2               Henry   16           Science
3              Steven   14           English
Extracted values of desired Column:
['Math', 'Social', 'Science', 'English']

方法 2:使用 '.loc[]' 方法

'.loc[]' 屬性返回 DataFrame 的指定列資料。

語法

 col_vals=df.loc[:,'col_name'].tolist()

示例

建立一個包含學生姓名、年齡和最喜歡的學科的表格,並使用 loc() 方法提取“最喜歡的學科”列的值。

演算法

  • 首先匯入所需的庫。

  • 根據要求建立一個表格。

  • 現在將表格作為變數 df 轉換為 DataFrame 物件。

  • 對 DataFrame df 應用屬性 'loc'。

  • 使用 '.tolist()' 方法將資料轉換為 Python 列表,因為我們的需求是列表。

  • 最後,使用內建的 'print()' 函式列印輸出。

import pandas as pd
import numpy as np
#creating a table

student_data={
   'Name of the Student': ['Alice', 'Cassie', 'Henry', 'Steven'],
   'Age':[15,13,16,14],
   'Favourite Subject':['Math', 'Social', 'Science', 'English']
}

#Now, we will turn the student_data table into Dataframe.
print("DataFrame that we created:")
df=pd.DataFrame(student_data)
print(df)

#tolist() is used to convert the column values into a list.
print("Extracted values of desired Column:")
col_vals=df.loc[:,'Favourite Subject'].tolist()
print(col_vals)

輸出

DataFrame that we created:
  Name of the Student  Age Favourite Subject
0               Alice   15              Math
1              Cassie   13            Social
2               Henry   16           Science
3              Steven   14           English
Extracted values of desired Column:
['Math', 'Social', 'Science', 'English']

方法 3:使用 ‘.iloc[]’ 方法

‘.iloc[]’ 屬性返回 DataFrame 的指定列資料或行資料,具體取決於作為引數傳遞給它的索引值。

語法

 col_vals=df.iloc[:,'col_index'].tolist()

示例

建立一個包含學生姓名、年齡和最喜歡的學科的表格,並使用 iloc() 方法提取“最喜歡的學科”列的值。

演算法

  • 首先匯入所需的庫。

  • 根據要求建立一個表格。

  • 現在將表格作為變數 df 轉換為 DataFrame 物件。

  • 對 DataFrame df 應用屬性 ‘iloc’。

  • 使用 ‘.tolist()’ 方法將資料轉換為 Python 列表,因為我們的需求是列表。

  • 最後,使用內建的 ‘print()’ 函式列印輸出。

import pandas as pd
import numpy as np
#creating a table

student_data={
   'Name of the Student': ['Alice', 'Cassie', 'Henry', 'Steven'],
   'Age':[15,13,16,14],
   'Favourite Subject':['Math', 'Social', 'Science', 'English']
}

#Now, we will turn the student_data table into Dataframe.
print("DataFrame that we created:")
df=pd.DataFrame(student_data)
print(df)
print("Extracted values of desired Column:")
col_vals=df.iloc[:,2].tolist()
print(col_vals)

輸出

DataFrame that we created:
  Name of the Student  Age Favourite Subject
0               Alice   15              Math
1              Cassie   13            Social
2               Henry   16           Science
3              Steven   14           English
Extracted values of desired Column:
['Math', 'Social', 'Science', 'English']

方法 4:使用 get() 函式

‘get()’ 函式從 DataFrame 返回列的值,或從字典返回鍵的值。

語法

 col_vals=df.get('col_name').tolist()

示例

建立一個包含學生姓名、年齡和最喜歡的學科的表格,並使用 get() 函式提取“最喜歡的學科”列的值。

演算法

  • 首先匯入所需的庫。

  • 根據要求建立一個表格。

  • 現在將表格作為變數 df 轉換為 DataFrame 物件。

  • 對 DataFrame df 應用函式 ‘get()’。

  • 使用 ‘.tolist()’ 方法將資料轉換為 Python 列表,因為我們的需求是列表。

  • 最後,使用內建的 ‘print()’ 函式列印輸出。

import pandas as pd
import numpy as np
#creating a table

student_data={
   'Name of the Student': ['Alice', 'Cassie', 'Henry', 'Steven'],
   'Age':[15,13,16,14],
   'Favourite Subject':['Math', 'Social', 'Science', 'English']
}

#Now, we will turn the student_data table into Dataframe.
print("DataFrame that we created:")
df=pd.DataFrame(student_data)
print(df)

#tolist() is used to convert the column values into a list.
print("Extracted values of desired Column:")
column_vals=df.get('Favourite Subject').tolist()
print(column_vals)

輸出

我們建立的 DataFrame

DataFrame that we created:
  Name of the Student  Age Favourite Subject
0               Alice   15              Math
1              Cassie   13            Social
2               Henry   16           Science
3              Steven   14           English
Extracted values of desired Column:
['Math', 'Social', 'Science', 'English']

結論

這些是從表格中提取特定列值列表的一些方法。但是,我們仍然可以建立更多方法來列出列值。例如,我們可以使用 for 迴圈遍歷列並列印列值列表。我們還可以使用 'apply()' 方法、'numpy.ravel()' 函式,甚至 'iteritems()' 方法。文章中討論的方法簡單易懂。

更新於: 2023年8月10日

5K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.