如何获取Pandas DataFrame中元素的精确位置?
查找Pandas DataFrame中元素的精确位置
假设元素存在且无重复,有两种简单方法可以获取它的整数位置(从0开始计数):
方法一:使用stack()结合索引定位
import pandas as pd df = pd.DataFrame({"A": [1,2,3], "B": [-2,8,1], "C": [-451,23,326]}) target = 326 # 将DataFrame堆叠为Series,获取目标元素的索引对 idx_pair = df.stack()[df.stack() == target].index[0] # 转换为整数行号和列号 row_num = df.index.get_loc(idx_pair[0]) col_num = df.columns.get_loc(idx_pair[1]) print(f"row:{row_num} col:{col_num}") # 输出 row:2 col:2
方法二:使用numpy.where()
这种方法更简洁,直接返回满足条件的位置数组:
import pandas as pd import numpy as np df = pd.DataFrame({"A": [1,2,3], "B": [-2,8,1], "C": [-451,23,326]}) target = 326 # 获取所有匹配位置的行、列数组,因元素唯一取第一个值 row_num, col_num = np.where(df == target) print(f"row:{row_num[0]} col:{col_num[0]}") # 输出 row:2 col:2
内容的提问来源于stack exchange,提问作者Telis
相关产品推荐
相关产品推荐

