Home > Software engineering >  Pandas column name missing depending on adressing
Pandas column name missing depending on adressing

Time:07-27

df.speed # so nice cause of autocomplete...
df['speed']
df.loc[:,'speed']

are returning my data like omitting the selected column name

Time
2022-07-27 11:33:16.279157    45.000000
2022-07-27 11:33:16.628157    44.928571
2022-07-27 11:33:17.093157    44.857143
2022-07-27 11:33:17.449157    44.785714

Why is that missing??

I want it like

df.filter(regex="speed")

which returns

                            speed
Time    
2022-07-27 11:33:16.279157  45.000000
2022-07-27 11:33:16.628157  44.928571
2022-07-27 11:33:17.093157  44.857143
2022-07-27 11:33:17.449157  44.785714
2022-07-27 11:33:17.885157  44.714286

which means only this can nicely easily plot with correct naming of the value axis

df.filter(regex="speed").plot()

enter image description here

whereas

df.speed.plot(label="speed")

only works by using plt.legend()

Is there a convenient way to do it?

CodePudding user response:

  • df['speed'] and df.speed return a Series.
  • df[['speed']] returns a DataFrame, which is what you're expecting.

CodePudding user response:

Add labels to each argument in your plot call corresponding to the series it is graphing, i.e. label = "Speed"

Then simply add Pyplot.legend() to the bottom of your script and the legend will display these labels.

df.speed.plot(label="speed")
plt.legend()

This should work, IMO

df.speed.plot(label="speed").legend()
  • Related