如何從 Pandas DataFrame 的單元格中獲取值?


要從 DataFrame 的單元格中獲取值,我們可以使用 indexcol 變數。

步驟

  • 建立一個二維、大小可變、可能非齊次的資料表格 df

  • 列印輸入的 DataFrame,df

  • 初始化 index 變數。

  • 初始化 col 變數。

  • 獲取對應於 indexcol 變數的單元格值。

  • 列印單元格值。

示例

 線上演示

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

更新於:14-Sep-2023

36K+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始
廣告