python - 比较 pandas DataFrame 和字典之间的数据
问题描述
我正在尝试在字典和 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 中的匹配行(键 'ax' 匹配列 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]
解决方案
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