如何从 Pandas DataFrame 的单元格中获取值?
pandasserver side programmingprogramming更新于 2025/4/30 7:37:17
要从 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