【问题标题】:finding values in pandas series - Python3在熊猫系列中查找值 - Python3
【发布时间】:2017-07-30 14:08:43
【问题描述】:

我有这个非常烦人的问题(我对 python 很陌生)

df=pd.DataFrame[{'col1':['1','2','3','4']}]

col1=df['col1']

为什么col1[1] in col1 返回False

【问题讨论】:

  • 你想要print (col1 == col1[1]) 吗?
  • 因为您正在尝试将 pandas 系列与标量值进行比较,您究竟想在这里做什么,测试您的值是否存在于列中的任何位置或哪些行相等?

标签: python-3.x pandas series


【解决方案1】:

检查值使用boolean indexing:

#get value where index is 1
print (col1[1])
2 
#more common with loc
print (col1.loc[1])
2

print (col1 == '2')
0    False
1     True
2    False
3    False
Name: col1, dtype: bool

如果需要获取行:

print (col1[col1 == '2'])
1    2
Name: col1, dtype: object

使用or检查多个值:

print (col1.isin(['2', '4']))
0    False
1     True
2    False
3     True
Name: col1, dtype: bool 

print (col1[col1.isin(['2', '4'])])
1    2
3    4
Name: col1, dtype: object

还有一些关于in 用于测试会员资格docs

Series 上使用 Python in 运算符测试索引中的成员资格,而不是值之间的成员资格。

如果这种行为令人惊讶,请记住,在 Python 字典中使用 in 测试的是键,而不是值,并且 Series 类似于 dict。要测试值的成员资格,请使用方法 isin()

对于 DataFrame,同样,in 适用于列轴,测试列名列表中的成员资格。

#1 is in index
print (1 in col1)
True

#5 is not in index
print (5 in col1)
False

#string 2 is not in index
print ('2' in col1)
False

#number 2 is in index
print (2 in col1)
True

您尝试在索引值中查找字符串2

print (col1[1])
2

print (type(col1[1]))
<class 'str'>

print (col1[1] in col1)
False

【讨论】:

  • 谢谢。帮助我更好地理解熊猫,但如果我需要一个布尔函数来表示单个值,我将如何做到这一点,因为isin() 需要一个列表
  • 添加[] 喜欢print (col1.isin(['2']))
  • 但如果只检查单个值,更简单的是print (col1 == '2'),它也更快
  • 但这仍然会给出 col1 的所有行的列表,它是真还是假对吗?有没有一种说法:(在伪代码中)`is '2' in col1` 只会返回 True(如果不是,则返回 False)
  • 是的,然后使用anyall 函数-print ((col1 == '2').any()) 检查是否至少有一个True,如果是,则返回True
【解决方案2】:

我可能遗漏了一些东西,这是几年后的事了,但是当我读到这个问题时,你正试图让 in 关键字在你的熊猫系列上工作?所以大概想做:

col1[1] in col1.values 

因为如上所述,pandas 是通过索引查看的,你需要专门要求它查看系列的值,而不是索引。

【讨论】:

    猜你喜欢
    • 2022-10-16
    • 2013-08-22
    • 1970-01-01
    相关资源
    最近更新 更多