I have a address table like this
JavaScript
x
6
1
City Area ID
2
AA BB 1
3
CC DD 2
4
EE FF 3
5
GG HH 4
6
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”
JavaScript
1
6
1
if name in df.City:
2
ID = df[df["City"] == name]["id"]
3
elif name in df.Area:
4
ID = df[df["Area"] == name]["id"]
5
6
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
)
JavaScript
1
5
1
if name in df.City.values:
2
ID = df[df["City"] == name]["id"].max()
3
elif name in df.Area.values:
4
ID = df[df["Area"] == name]["id" ].max()
5