简体   繁体   中英

Changing variable in a loop

i tried a lot of different things its either error or it adds literly just 1 of the value. Im trying that after every loop iteration it changes from group_1 to group_2. If i solely put group_1 then it works but that is not the goal.

i would like to hear out your ideas.

import plotly.graph_objects as go
fig = go.Figure()



species = ["Adelie", "Gentoo", "Chinstrap"]

group_1 = df[df['species'] == 'Adelie']['culmen_depth_mm']
group_2 = df[df['species'] == 'Chinstrap']['culmen_depth_mm']
group_3 = df[df['species'] == 'Gentoo']['culmen_depth_mm']

froup_1 = df[df['species'] == 'Adelie']['culmen_length_mm']
froup_2 = df[df['species'] == 'Chinstrap']['culmen_length_mm']
froup_3 = df[df['species'] == 'Gentoo']['culmen_length_mm']



### code
#for i, col in range(3):
for i, col in enumerate(species, 0):
    group = group_ + i
    fig.add_trace(go.Scatter(x = group , y = froup, mode ='markers', name = col ))
    
  
    
    


fig.update_layout()
fig.show()

I'm not sure I'm understanding the question correctly, but you could make a list with your groups inside, and just loop over this list instead of the species variable, like so:

species_names = ["Adelie", "Gentoo", "Chinstrap"]

group_1 = df[df['species'] == 'Adelie']['culmen_depth_mm']
group_2 = df[df['species'] == 'Chinstrap']['culmen_depth_mm']
group_3 = df[df['species'] == 'Gentoo']['culmen_depth_mm']

fgroup_1 = df[df['species'] == 'Adelie']['culmen_length_mm']
fgroup_2 = df[df['species'] == 'Chinstrap']['culmen_length_mm']
fgroup_3 = df[df['species'] == 'Gentoo']['culmen_length_mm']

species = [group_1, group_2, group_3]
fspecies = [fgroup1, fgroup_2, fgroup_3]

for i, group in enumerate(species):
    fig.add_trace(go.Scatter(x=group, y=fspecies[i], mode='markers', name=species_names[i]))


fig.update_layout()
fig.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM