user3779226
user3779226

Reputation: 31

python pandas loc return empty dataframe

I am trying to get the subset dataframe using the below code:

dprev = "eiffel tower"

df.loc[df['place'] == dprev] -> returns empty

drandom = random.choice(df['place'].unique())

df.loc[df['place'] == drandom] -> returns the subset

why am i not seeing the same thing when dprev is string variable?

Upvotes: 0

Views: 9286

Answers (3)

Joe
Joe

Reputation: 12417

Try in this way:

dprev = "eiffel tower"
df = df.loc[df['place'].str.lower() == dprev]

or:

df = df.loc[df['place'].str.lower().str.contains(dprev)]

Upvotes: 0

Rakesh
Rakesh

Reputation: 82765

Can you try using str.contains with case=False

Ex:

import pandas as pd

dprev = "eiffel tower"
df = pd.DataFrame({"place": ["eiffel tower", "Eiffel tower", "Hello"], "data":[1,2,3]})
print(df.loc[df['place'].str.contains(dprev, case=False)])

Output:

   data         place
0     1  eiffel tower
1     2  Eiffel tower

Upvotes: 1

Nihal
Nihal

Reputation: 5334

for this you don't have to use df.loc

dprev = "eiffel tower"

df[df['place'] == dprev] 

See this answer

Upvotes: 0

Related Questions