如何在Pandas DataFrame中定位指定字符串的位置
解决方案
方法一:使用np.where直接获取位置索引
np.where会返回匹配元素的行和列索引数组,取第一个匹配项即可得到目标位置:
import numpy as np target_date = '2022-05-29' # 获取所有匹配位置的行、列索引 rows, cols = np.where(grid_table == target_date) # 转换为[行位置, 列位置]格式(取第一个匹配结果) position = [int(rows[0]), int(cols[0])] print(position) # 输出: [0, 0]
方法二:通过堆叠DataFrame查找标签后转换为位置
如果需要先获取行/列标签再转位置,可采用堆叠方式:
# 将DataFrame堆叠为带索引的Series stacked_df = grid_table.stack().reset_index() # 筛选目标日期对应的行 match_row = stacked_df[stacked_df[0] == target_date].iloc[0] # 将标签转换为整数位置 row_pos = grid_table.index.get_loc(match_row['level_0']) col_pos = grid_table.columns.get_loc(match_row['level_1']) position = [row_pos, col_pos] print(position) # 输出: [0, 0]
你的错误原因说明
grid_table.where([grid_table == '2022-05-29'] == True):将布尔DataFrame包裹进列表后与True比较,得到的是单个布尔值,而where要求传入与原DataFrame同形状的布尔数组,因此触发维度不匹配错误。[grid_table == '2022-05-29'] == True:列表与布尔值直接比较,逻辑无意义,返回False是必然结果。grid_table[grid_table == '2022-05-29']:这种索引方式会保留所有行列结构,仅将不匹配位置设为NaN,因此会显示整个表格而非仅匹配区域。grid_table.loc[grid_table == '2022-05-29']:loc不支持多维布尔索引,因此抛出错误。
内容的提问来源于stack exchange,提问作者Henul
相关产品推荐
相关产品推荐

