Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

python - Pandas says 7 in df["C"] but actually asking for the indices of 7 returns empy list - why?

I have a dataframe with a couple of thousand lines. One column is called C and it is of interest to know whether the number 7 occurs in the column.

I tried: print(7 in df["C"]) and it returned True, however print(df.index[df["C"] == 7].tolist()) returns [].

What is going on here? What aspect of in am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because in check value of indices, it is gotcha:

df = pd.DataFrame({
    'A': ['a','a','a','a','b','b','b','c','d'],
    'C': list(range(10, 19))
})
print (df)
   A   C
0  a  10
1  a  11
2  a  12
3  a  13
4  b  14
5  b  15
6  b  16
7  c  17
8  d  18

print(7 in df["C"])
True

print(10 in df["C"])
False

And in column C is no value 7, so returned empty list:

print(df.index[df["C"] == 7].tolist())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...