我有这个令人难以忍受的烦恼问题(我对python很新)
df=pd.DataFrame[{'col1':['1','2','3','4']}]
col1=df['col1']
为什么col1[1] in col1
会返回False
?
答案 0 :(得分:3)
对于支票值,请使用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():
对于DataFrames,同样适用于列轴,测试列名列表中的成员资格。
#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
答案 1 :(得分:0)
我可能会丢失一些东西,这是几年后的事,但是当我读到这个问题时,您正在尝试使用in
关键字来处理您的熊猫系列吗?所以大概想做:
col1[1] in col1.values
由于如上所述,pandas正在浏览索引,因此您需要专门要求它查看序列的值,而不是索引。