在 pandas 系列中查找值 - Python3

mys*_*man 6 series python-3.x pandas

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

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

col1=df['col1']
Run Code Online (Sandbox Code Playgroud)

为何col1[1] in col1返回False

jez*_*ael 9

对于检查值,请使用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
Run Code Online (Sandbox Code Playgroud)

如果需要获取行:

print (col1[col1 == '2'])
1    2
Name: col1, dtype: object
Run Code Online (Sandbox Code Playgroud)

要使用以下命令检查多个值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
Run Code Online (Sandbox Code Playgroud)

还有一些关于in测试会员文档的信息:

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

如果这种行为令人惊讶,请记住,在 Python 字典上使用 in 测试键,而不是值,并且 Series 类似于字典。要测试值中的成员资格,请使用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
Run Code Online (Sandbox Code Playgroud)

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

print (col1[1])
2

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

print (col1[1] in col1)
False
Run Code Online (Sandbox Code Playgroud)