如何按列名及行值筛选Pandas DataFrame目标列序列
Pandas重名列按指定行值精准提取方案
核心逻辑:重名列无法仅靠列名定位时,先筛选同名列子集,再通过指定索引行的取值做二次布尔匹配,最终提取唯一目标列。
- 第一步:筛选所有列名匹配目标名称的列子集
直接使用基础列索引写法即可:test_part_cols = df.loc[:, "TestPart"] - 第二步:在子集内匹配指定行的目标值,提取唯一列
针对Location行取值为Plant的筛选条件,用列方向布尔索引定位,再用squeeze()把单列DataFrame转为一维序列:result = test_part_cols.loc[:, test_part_cols.loc["Location"] == "Plant"].squeeze()
完整验证代码
import pandas as pd # 构造示例数据 df = pd.DataFrame( [ ["Plant", "Factory", "Plant"], [25, 56, 30], [5, 10, 15], ["A", "B", "C"] ], index=["Location", "Lead Time", "Value1", "Value2"], columns=["TestPart", "TestPart", "OtherPart"] ) df.index.name = "attribute" # 执行筛选 test_part_subset = df.loc[:, "TestPart"] final_col = test_part_subset.loc[:, test_part_subset.loc["Location"] == "Plant"].squeeze()
执行后final_col的输出完全匹配预期:
attribute Location Plant Lead Time 25 Value1 5 Value2 A Name: TestPart, dtype: object
说明:只要保证「列名+指定行取值」的组合能唯一命中一列,
squeeze()就会返回标准的Pandas Series格式结果;如果存在多列同时满足条件,返回值会是多列DataFrame,可根据业务校验规则自行加唯一性判断。
内容的提问来源于stack exchange,提问作者Daniel Mashburn
相关产品推荐
相关产品推荐

