python - 如何按局部最小值对 Pandas DataFrame 进行分组?
问题描述
最初,我有一个Pandas DataFrame
由两列组成的,A (for x-axis values)
并被B (for y-axis values)
绘制成一个简单的x-y coordinate graph
. 数据由几个峰组成,其中所有峰都以相同的y-axis
值以相同的增量出现。因此,我能够做到以下几点:
df = pd.read_csv(r'/Users/_______/Desktop/Data Packets/Cycle Data.csv')
nrows = int(df['B'].max() * 2) - 1
alphabet: list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
groups = df.groupby(df.index // nrows)
for (frameno, frame) in groups:
frame.to_csv("/Users/_______/Desktop/Cycle Test/" + alphabet[frameno] + "%s.csv" % frameno, index=False)
上面的代码将大循环数据文件解析成许多相同大小的数据文件,因为每个循环的局部最小值和最大值是相同的。
但是,我希望能够解析具有任意峰值和最小值的数据文件。我不能同时拆分大数据文件,因为每个数据文件的大小不同。这是一个示例说明:
编辑:样本数据(A
是x轴,B
是y轴):
data = {'A': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26], 'B': [0, 1, 2, 3, 4, 5, 6, 7, 5, 3, 1, -1, 1, 3, 5, 7, 9, 8, 7, 6, 5, 4, 6, 8, 6, 4, 2]}
df = pd.DataFrame(data)
编辑 2:不同的样本数据(Displacement
从 1 到 50 回到 1,然后从 1 到 60 回到 1,等等):
Load Displacement
0 0.100000 1.0
1 0.101000 2.0
2 0.102000 3.0
3 0.103000 4.0
4 0.104000 5.0
.. ... ...
391 0.000006 5.0
392 0.000005 4.0
393 0.000004 3.0
394 0.000003 2.0
395 0.000002 1.0
解决方案
col = df['B'] # replace with the appropriate column name
# find local minima. FIXED: use rightmost min value if repeating
minima = (col <= col.shift()) & (col < col.shift(-1))
# create groups
groups = minima.cumsum()
# group
df.groupby(groups).whatever() # replace with whatever the appropriate aggregation is
示例,计数值:
df.groupby(groups).count()
Out[10]:
A B
B
0 11 11
1 10 10
2 6 6
推荐阅读
- oracle - 将大型 Oracle 表下载到 csv 文件
- r - 用 0 替换重复值
- sql - 是否有 SQL 更新查询来更新同一用户 ID 内的多条记录的相同值?
- python - Scons 在编译代码时打印许可错误
- php - WordPress 评论未显示,我是否使用了正确的代码?
- java - Method only applicable on single Instance of Class instead of ArrayList
- c# - 如何创建具有自引用 EFCore 的模型
- angular - 如果我们提供更多的@Input() 属性来为子组件提供数据,会有什么影响吗?如果是,那么限制应该是多少?
- java - 如何使用 Jackson 将单个 JSON 属性映射到多个对象?
- java - 在 org.hibernate.ScrollableResults 之后,使用 spring-boot 进行休眠不会释放连接