Skip to content
Advertisement

How to check a value in which column in dataframe

I have a address table like this

City  Area  ID
 AA    BB   1
 CC    DD   2 
 EE    FF   3 
 GG    HH   4

I need to extract the ID when I got a name. However, I don’t know the name is a City name or Area name. So I want to use conditional check the name in City or Area and then extract the ID I have tried this method, but it was not run for me.

By the way the name is a string. Ex. name = “AA”

if name in df.City:
  ID = df[df["City"] == name]["id"]
elif name in df.Area:
  ID = df[df["Area"] == name]["id"]

Any other good solution?

Advertisement

Answer

Try this way:

.values will give you an array therefore your if statement can be true, but simply the id would return a series object – I guess you only want the number 1 or 2… therefore if you take the .max(), that will give you the number also if you pass a name that is not in there it will be an empty object and should not fail (unlike you did it with iloc)

if name in df.City.values:
   ID = df[df["City"] == name]["id"].max()
elif name in df.Area.values:
   ID = df[df["Area"] == name]["id" ].max()
Advertisement