首页 > 解决方案 > 检测变化是列值和绘图

问题描述

第 2 列中的我的数据(此处以标题名称N显示)包括从 0 到 15 或从 0 到 7 等重复的循环数。第 3 列CN由下式计算CN = np.cumsum(np.abs(np.diff(N)))

我想根据CN值从数据中获取切片。从值 1 到 14 以及从值 29-36 等等,然后绘制NCN。我面临的问题是我必须在绘图之前手动检查切片的CN值。我想要一个程序,它可以在CN值突然跳跃时对数据进行切片然后绘图


+-------+-----+----+-------+
| index |  N  | CN | Vdiff |
+-------+-----+----+-------+
|   524 |   2 |  1 |   0.0 |
|   525 | 2   |  1 |   0.0 |
|   526 |   2 |  1 |   0.0 |
|     . |     |    |       |
|     . |     |    |       |
|  5900 |  15 | 14 |   0.0 |
|  5901 |  15 | 29 |   0.1 |
|  5902 |   0 | 29 |   0.0 |
|     . |     |    |       |
|     . |     |    |       |
| 33001 |   7 | 36 |   0.0 |
| 33002 |   7 | 36 |   0.0 |
| 33003 |   7 | 43 |   0.1 |
| 33004 |   0 | 43 |   0.0 |
+-------+-----+----+-------+
import matplotlib.pyplot as plt
flt1 = (data['CN'] > 0) & (data['CN'] <= 14) 
Amp1 = data.loc[flt1] 

flt2 = (data['CN'] > 30) & (data['CN'] <= 36)   
Amp2 = data.loc[flt2]  

Amp1.plot(x='N',y='CN',kind='line')

标签: pythonpandasdataframenumpymatplotlib

解决方案


如果我正确理解了您的问题,您希望在 CN 的跳跃之间生成图。然后,下面的代码应该做到这一点:

import matplotlib.pyplot as plt

jump_size = 5 # the size of what you consider to be a "jump" in CN
idx = list( data.index[data.CN.diff() >= jump_size] + 1 ) # find jump indexes

# if necessary, add the first index and the last index of your data
if idx[0] != 0: idx = [0]+idx
if idx[-1] != data.shape[0]: idx = idx+[None]

# produce plots between the jumps in CN
for imin,imax in zip(idx[:-1], idx[1:]):
    data.iloc[imin:imax].plot(x='N',y='CN',kind='line')
    plt.show()

让我知道这是否会产生您想要的结果。

编辑:根据评论中的要求,这里是与for以前相同的循环,但使用 matplotlib 绘图而不是直接从 pandas 数据框绘图:

for imin,imax in zip(idx[:-1], idx[1:]):
    data_slice = data.iloc[imin:imax]
    plt.plot(data_slice.N, data_slice.CN)
    plt.show()

推荐阅读