Peaceful
Peaceful

Reputation: 5450

Plot all the values in a row against the index in pandas

I have a daframe df:

    beat1   beat2   beat3   beat4   beat5   beat6   beat7   beat8   beat9  
0  0.6839  0.8879  0.7543  0.4805  0.8528  0.6982  0.5520  0.6154  0.6579   
1  1.0380  0.4868  0.3099  0.4994  0.7509  0.4649  0.5080  0.4040  0.7537   
2  0.7116  0.8063  0.6754  0.7365  0.9517  0.6420  0.8108  0.9082  0.7132   
3  0.7296  0.7389  0.7227  0.7623  0.7424  0.7457  0.8250  0.7064  0.7792   
4  0.8912  0.8617  0.8189  0.8118  0.6574  0.8882  0.6544  0.8296  0.9344

Now, I want to plot all the values in a given row as a function of index values [0, 1, 2, 3, 4]. I can achieve this using a following code:

for i in df.index:
    vals = df.loc[i]
    for val in vals:
        plt.scatter(i, val,c='g')

plt.show()

However, there must be a way to do the same without using nested for loops since it is slow for larger dataframes and I need to do this multiple times. Any ideas?

Upvotes: 2

Views: 3223

Answers (2)

piRSquared
piRSquared

Reputation: 294288

plt.scatter(df.index.values.repeat(len(df.columns)), df.values.ravel())

enter image description here


df.stack().reset_index(0).plot.scatter('level_0', 0)

enter image description here

Upvotes: 1

DYZ
DYZ

Reputation: 57033

You can apply the scatter plot to each row:

df.apply(lambda x: plt.scatter(x.index, x, c='g'))
plt.show()

Upvotes: 2

Related Questions