Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access multiple values from same row of a dataframe

I have a dataframe containing information about pokemon, and I want to create a pokemon object from a row of the dataframe. Here is my code:

sets = pd.read_excel("SetsSheet.xlsx", index_col=0, header=0)

def fromset(setindex):
    hp = sets.loc[setindex, "hp"]
    type1 = sets.loc[setindex, "type 1"]
    type2 = sets.loc[setindex, "type 2"]
    move1 = sets.loc[setindex, "move 1"]
    move2 = sets.loc[setindex, "move 2"]
    learnset = [move1, move2]
    return BattlePokemon(name, type1, type2, hp, learnset)

This code works fine, but it repeats itself a lot, so I suspect there’s a better way I’m supposed to do this, and I want to know what it is.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can create list of columns and select by them:

def fromset(setindex):
    
    cols = ["hp", "type 1","type 2", "move 1", "move 2"]
    hp, type1, type2, move1, move2  = sets.loc[setindex, cols]
    learnset = [move1, move2]
    return BattlePokemon(name, type1, type2, hp, learnset)

Also is possible use unpacking for 2 last values to list with *:

def fromset(setindex):
    
    cols = ["hp", "type 1","type 2", "move 1", "move 2"]
    hp, type1, type2, *learnset  = sets.loc[setindex, cols]
    return BattlePokemon(name, type1, type2, hp, learnset)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading