繁体   English   中英

select 值基于 pandas dataframe 中的 pandas 中的条件

[英]select values based on condition on multiple columns for pandas dataframe in python

这是我的 dataframe 暗淡

          var         types     count
0         var1       nominal      1
1         var2       ordinal      1
2         var3  quantitative      2
3         var4  quantitative      2

我想得到 dim["var"] 其中 dim["types"] == 定量和 dim["count"] > 1。然后结果是一个列表 [var3, var4]。 当我尝试以下查询时:

print(dim["var"].where((dim["types"] =="quantitative") & (dim["count"] > 1)))

我得到以下结果:

0    NaN
1    NaN
2    NaN
3    NaN

我不知道如何获得所需的解决方案。

使用带有掩码的DataFrame.loc

L = dim.loc[(dim["types"] =="quantitative") & (dim["count"] > 1), "var"].tolist()
print (L)
['var3', 'var4']

您的 output 是正确的,因为Series.where将 where 条件为False的值转换为缺失值:

print ((dim["types"] =="quantitative") & (dim["count"] > 2))
0    False
1    False
2    False
3    False
dtype: bool

print(dim["var"].where((dim["types"] =="quantitative") & (dim["count"] > 2)))
0    NaN
1    NaN
2    NaN
3    NaN
Name: var, dtype: object

因此,如果在条件 output 中使用==是:

print ((dim["types"] =="quantitative") & (dim["count"] > 1))
0    False
1    False
2     True
3     True
dtype: bool

print(dim["var"].where((dim["types"] =="quantitative") & (dim["count"] > 1)))
0     NaN
1     NaN
2    var3
3    var4
Name: var, dtype: object 

loc访问器与您的掩码一起使用。

>>> (dim["types"] == "quantitative") & (dim["count"] > 1)
0    False
1    False
2     True
3     True
dtype: bool

像这样:

>>> dim.loc[(dim["types"] == "quantitative") & (dim["count"] > 1), 'var']
2    var3
3    var4
Name: var, dtype: object

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM