简体   繁体   中英

Plot graph of difference in one column for grouped columns of pandas dataframe

I have a dataframe, a simplified example is below:

   cycle  sensor  value
0      0       1   0.34
1      0       1   0.80
2      0       2   0.12
3      0       2   0.62
4      1       1   0.01
5      1       1   0.75
6      1       2   0.06
7      1       2   0.02

I'd like to plot the difference of the "value" column for each sensor, for each cycle: have x-axis as cycle number, y-axis as the difference in value, each series would be a given sensor number. eg the line for sensor one would be 0.46 and 0.74 over cycles 0 and 1.

In reality, I have many more columns (not used for this part of my code) and there are 144 cycles and 37 cycles. There are a few thousand values per sensor per cycle.

This is the code I have written, I don't get an error: a figure is created but no data shows.

groups = unstacked_data.groupby(["cycle", "pressure"])

fig,ax = plt.subplots()
ax.set_xlabel("Cycle Number")
ax.set_ylabel("Change in Normalised Pressure")


for cycle, group in groups:
        ax.plot(cycle[0],group.value.max()-group.value.min(), label=group.pressure)

I'm not sure what I'm doing wrong, any advice would be appreciated! :)

Ok, I think now I get it. Should the result look like this?

diff = df.groupby(["sensor","cycle"]).apply(lambda x:x.value.max()-x.value.min()).unstack()

#Output: each value in the table is max-min. Columns are cycles and rows are sensors
    cycle   0         1
sensor      
1          0.46     0.74
2          0.50     0.04

And now you can plot it by row, ie by sensor.

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