Mr.Mister.
Mr.Mister.

Reputation: 37

Conditioning over list element in Data Frame columns

Getting data from API, and for one item there is lots of data so I decided to put them into a List. Now I have Data Frame with a column containing List elements. I want to write a function which is checking some conditions, e.g. who is the best based on ability and stats. Something like whoIsTheBest('fire-punch', 'speed'), where fire-punch is in "move" column, and speed value in "speed" column (it has most speed and can do that "move").

I have an issue accessing elements List elements from a column "move". This is how I fetched the data:

for x in elements:
    url = "https://pokeapi.co/api/v2/pokemon/" + str(x["entry_number"]) + "/"
    get_pokemon = requests.get(url)
    get_pokemon_json = get_pokemon.json()
    d = {'id': x["entry_number"], 
         'name': x["pokemon_species"]["name"],
         'special_defense': get_pokemon_json["stats"][1]["base_stat"],
         'special_attack': get_pokemon_json["stats"][2]["base_stat"],
         'defense': get_pokemon_json["stats"][3]["base_stat"],
         'attack': get_pokemon_json["stats"][4]["base_stat"],
         'hp': get_pokemon_json["stats"][5]["base_stat"],
         'move': list(y['move']['name'] for y in get_pokemon_json['moves']),
         'type': list(z['type']['name'] for z in get_pokemon_json['types'])
        }  
    all_data.append(d)
df1 = pd.DataFrame(all_data)



             move        name  \
0    [razor-wind, swords-dance, cut, bind, vine-whi...   bulbasaur   
1    [swords-dance, cut, bind, vine-whip, headbutt,...     ivysaur 

Tried with the following:

if 'fire-punch' in str(df1["move"]):

but getting TypeError: 'list' object is not callable

Is there maybe better approach for creating column values instead of List or is there some way I can access each element? And is there a reason that elements are in [] parentheses?

Upvotes: 0

Views: 58

Answers (1)

Jim Todd
Jim Todd

Reputation: 1588

df1["move"] is a column and has a set of values (can be considered Series as per pandas). So its not a string. Thats throwing the error.

Instead you can check it like this:

for item in df1.move.values:
   if 'fire-punch' in item:
       print("Yes, its found in: ", item)

Also, I see each row is a list in this case.

Upvotes: 1

Related Questions