如何从 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP