如何从 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+ 浏览量

开启你的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.