【问题标题】:Comparing data between pandas DataFrame and dictionary比较 pandas DataFrame 和字典之间的数据
【发布时间】:2025-12-01 08:10:01
【问题描述】:

我正在尝试在字典和 pandas DataFrame 之间进行一些比较。

DataFrame 如下所示:

      A      B     C
0    'a'    'x'    0
1    'b'    'y'    1
2    'c'    'z'    4

字典看起来像这样:

{
'a-x': [1],
'b-y': [2],
'c-z': [3]
}

目标是使用字典键识别DataFrame中匹配的行(键'a-x'匹配A列和B列的索引0),然后识别C列中大于关联值的DataFrame数据字典。

所以:

key 'a-x' matches index 0 of column A and column B, but value of 0 in C is less than 1 > exclude
key 'b-y' matches index 1 of column A and column B, but value of 1 in C is less than 2 > exclude
key 'c-z' matches index 2 of column A and column B, and value of 4 in C is greater than 3 > include

过滤后的 DataFrame 将只包含索引 2 处的条目,如下所示:

      A      B     C
2    'c'    'z'    4

如果有一些重要的细节,这是我的实际数据的样本

数据帧:

    Chrom   Loc         WT  Var Change  ConvChange  AO  DP  VAF IntEx    Gene   Upstream    Downstream  Individual  ID
0   chr1    115227854   T   A   T>A     T>A         2   17224   0.0116117   TIII    TIIIa   NaN NaN 1   113.fastq/onlyProbedRegions.vcf

字典:

rates =
{
    'chr1-115227854-T-A': [0.0032073647185113397]
}

代码:

return df[(df.Chrom+'-'+str(df.Loc)+'-'+df.WT+'-'+df.Var).map(pd.Series(rates).str[0])<df.VAF]

【问题讨论】:

    标签: python pandas dictionary dataframe


    【解决方案1】:

    创建pd.Series 然后使用map 创建布尔索引

    d={
    'a-x': [1],
    'b-y': [2],
    'c-z': [3]
    }
    pd.Series(d)
    Out[335]:
    a-x    [1]
    b-y    [2]
    c-z    [3]
    dtype: object
    
    
    df[(df.A+'-'+df.B).map(pd.Series(d).str[0])<df.C]
    Out[340]: 
       A  B  C
    2  c  z  4
    

    【讨论】:

    • 感谢您的帮助,但我似乎无法正常工作。如果有细微差别导致这种情况,我确实在我的问题中添加了实际数据,并且它们的代码是我根据您的回复改编的。但无论我尝试什么,我总是返回一个空的 DataFrame。
    • 调试你的字符串连接代码(看看输出!)。 str(df.Loc) 可能是问题所在,您可能需要df.Loc.astype(str)