在 pandas 系列中寻找价值-Python3 [英] finding values in pandas series - Python3
问题描述
我遇到了一个令人烦恼的问题(我对python还是很陌生的)
i have this excruciatingly annoying problem (i'm quite new to python)
df=pd.DataFrame[{'col1':['1','2','3','4']}]
col1=df['col1']
为什么col1[1] in col1
返回False
?
推荐答案
对于检查值,请使用 boolean indexing
:
For check values use 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
And something about in
for testing membership docs:
在
Series
上使用Python in运算符测试索引中的成员身份,而不是值中的成员身份.
Using the Python in operator on a
Series
tests for membership in the index, not membership among the values.
如果这种行为令人惊讶,请记住,在Python字典上使用in会测试键,而不是值,而Series则类似于dict.要测试值中的成员资格,请使用方法 isin():
If this behavior is surprising, keep in mind that using in on a Python dictionary tests keys, not values, and Series are dict-like. To test for membership in the values, use the method isin():
对于DataFrames,同样适用于列轴,测试列名称列表中的成员资格.
For DataFrames, likewise, in applies to the column axis, testing for membership in the list of column names.
#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
:
You try to find string 2
in index values:
print (col1[1])
2
print (type(col1[1]))
<class 'str'>
print (col1[1] in col1)
False
这篇关于在 pandas 系列中寻找价值-Python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!