如何從 Pandas DataFrame 的單元格中獲取值?
要從 DataFrame 的單元格中獲取值,我們可以使用 index 和 col 變數。
步驟
建立一個二維、大小可變、可能非齊次的資料表格 df。
列印輸入的 DataFrame,df。
初始化 index 變數。
初始化 col 變數。
獲取對應於 index 和 col 變數的單元格值。
列印單元格值。
示例
import pandas as pd df = pd.DataFrame( { "x": [5, 2, 1, 9], "y": [4, 1, 5, 10], "z": [4, 1, 5, 0] } ) print("Input DataFrame is:
", df) index = 2 col = "y" cell_val = df.iloc[index][col] print "Cell value at ", index, "for column ", col, " : ", cell_val index = 0 col = "x" cell_val = df.iloc[index][col] print "Cell value at ", index, "for column ", col, " : ", cell_val index = 1 col = "z" cell_val = df.iloc[index][col] print "Cell value at ", index, "for column ", col, " : ", cell_val
輸出
Input DataFrame is: x y z 0 5 4 4 1 2 1 1 2 1 5 5 3 9 10 0 Cell value at 2 for column y: 5 Cell value at 0 for column x: 5 Cell value at 1 for column z: 1
廣告