0
\$\begingroup\$

My code calls 1 column of a dataframe, turns it into an array and plots it. I want to able to do this for all the columns without having to repeat the code many times.

How can I do this?

#Code to create fake data
df = pd.DataFrame(np.random.rand(10,5), columns=list('abcde'),
     index=list('nopqrstuvw'))
df.columns.name = 'level_0'
df.index.name = 'level_1'



#I load an array of shape (10, 2)
sensors_pos = sio.loadmat('/home/Coord_Slp_2D.mat')['Cor']


# I extract column "a"
df1=df['Total Acc'].round(4)*100
df2=df1.reset_index().pivot('level_1', 'level_0', 'Total Acc')

df3=df2['a'].reset_index() #extracts the column "a"


#Turns column "a" into an array
data=df3['a'].values   


#Plots column "a"
fig = plt.figure(figsize = (8,5))
ax,_ = plot_topomap(data, sensors_pos, cmap='viridis', show=False) 
plt.title('a')
fig.colorbar(ax)
fig.show()


#------------------------------
#This is where the repetition starts. I will have to do this for each column

 # I extract column "b"

df4=df2['b'].reset_index() #extracts the column "b"


#Turns column "b" into an array
data=df3['b'].values   


#Plots column "b"
fig = plt.figure(figsize = (8,5))
ax,_ = plot_topomap(data, sensors_pos, cmap='viridis', show=False) 
plt.title('b')
fig.colorbar(ax)
fig.show()
\$\endgroup\$
1
\$\begingroup\$

I added a "for" loop. :)

#Code to create fake data
df = pd.DataFrame(np.random.rand(10,5), columns=list('abcde'),
index=list('nopqrstuvw'))
df.columns.name = 'level_0'
df.index.name = 'level_1'

#I load an array of shape (10, 2)
sensors_pos = sio.loadmat('/home/Coord_Slp_2D.mat')['Cor']


# I extract each column. From "a" to "e"
df1=df['Total Acc'].round(4)*100
df2=df1.reset_index().pivot('level_1', 'level_0', 'Total Acc')


for column in df2:
    data=df2[column].values
    fig = plt.figure(figsize = (8,5))
    ax,_ = plot_topomap(data, sensors_pos, cmap='viridis', show=False) 
    fig.colorbar(ax)
    fig.show()
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.