python - 根据存储在字典中的条件从 Pandas 数据框中选择数据

标签 python pandas dataframe

我有一个包含大量变量的 Pandas 数据框。这可以简化为:

tempDF = pd.DataFrame({ 'var1': [12,12,12,12,45,45,45,51,51,51],
                        'var2': ['a','a','b','b','b','b','b','c','c','d'],
                        'var3': ['e','f','f','f','f','g','g','g','g','g'],
                        'var4': [1,2,3,3,4,5,6,6,6,7]})

如果我想选择数据帧的一个子集(例如 var2='b' 和 var4=3),我会使用:

tempDF.loc[(tempDF['var2']=='b') & (tempDF['var4']==3),:]

但是,如果匹配条件存储在字典中,是否可以选择数据帧的子集,例如:

tempDict = {'var2': 'b','var4': 3}

重要的是变量名不是预定义的,dict 中包含的变量数量是可变的。

我已经为此困惑了一段时间,所以任何建议将不胜感激。

最佳答案

您可以评估一系列条件。它们不必只是相等。

df = tempDF
d = tempDict

# `repr` returns the string representation of an object.    
>>> df[eval(" & ".join(["(df['{0}'] == {1})".format(col, repr(cond)) 
       for col, cond in d.iteritems()]))]
   var1 var2 var3  var4
2    12    b    f     3
3    12    b    f     3

看看 eval 在这里做了什么:

conditions = " & ".join(["(df['{0}'] == {1})".format(col, repr(cond)) 
       for col, cond in d.iteritems()])

>>> conditions
"(df['var4'] == 3) & (df['var2'] == 'b')"

>>> eval(conditions)
0    False
1    False
2     True
3     True
4    False
5    False
6    False
7    False
8    False
9    False
dtype: bool

这是另一个使用等式约束的例子:

>>> eval(" & ".join(["(df['{0}'] == {1})".format(col, repr(cond)) 
                      for col, cond in d.iteritems()]))
d = {'var2': ('==', "'b'"),
     'var4': ('>', 3)}

>>> df[eval(" & ".join(["(df['{0}'] {1} {2})".format(col, cond[0], cond[1]) 
       for col, cond in d.iteritems()]))]
   var1 var2 var3  var4
4    45    b    f     4
5    45    b    g     5
6    45    b    g     6

另一种选择是使用 query :

qry = " & ".join('{0} {1} {2}'.format(k, cond[0], cond[1]) for k, cond in d.iteritems())

>>> qry
"var4 > 3 & var2 == 'b'"

>>> df.query(qry)
   var1 var2 var3  var4
4    45    b    f     4
5    45    b    g     5
6    45    b    g     6

关于python - 根据存储在字典中的条件从 Pandas 数据框中选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35882501/

相关文章:

python - 如何迭代一行并相互比较?

python - virtualenv 使用升级后的系统默认 pip

python - 从 pandas 数据帧整体返回最大值,而不是基于列或行

python-2.7 - 在 Python “html5lib not found” 中读取 html 到数据框时出错

python - Pandas:更快地将字符串元组列表转换为数据帧?

Python - PyQt4 窗口选项未显示在制作窗口的角落

python - 如何设置始终加密的 Azure SQL 数据库并用数据填充它?

python - 使用迭代器迭代不同的数据帧

python - 如果列值的组合等于列表中的元组,则删除 Pandas 中的 dataFrame 行

python :Select the rows for the most recent entry from multiple users