python - 检测变化是列值和绘图
问题描述
第 2 列中的我的数据(此处以标题名称N显示)包括从 0 到 15 或从 0 到 7 等重复的循环数。第 3 列CN由下式计算CN = np.cumsum(np.abs(np.diff(N)))
我想根据CN值从数据中获取切片。从值 1 到 14 以及从值 29-36 等等,然后绘制N和CN。我面临的问题是我必须在绘图之前手动检查切片的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')
解决方案
如果我正确理解了您的问题,您希望在 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()
推荐阅读
- sql - 查找至少喜欢 2 的人的查询
- symfony - 在 Symfony 4.2 中捆绑安装后如何运行脚本或方法?
- jquery - 如何找到 iOS 应用程序的播放音频路径?
- c# - 尝试为文件“”附加自动命名数据库失败
- android - 使用 altbeacon 停止和重新启动前台服务扫描
- vba - 在 PrintOptions 下添加范围并在变量中确定它
- asp.net - 如何让 dropdownlist_selectedindexchange 先触发
- charts - 在 Google Chart 上显示独立的 x 轴系列
- xamarin - Xamarin 是否将 Forms 应用程序转换为 Java,如果没有,那么它如何在 Android 上运行?
- generics - 如何在 Rust 中转换泛型原始类型?