首页 > 解决方案 > 如何按局部最小值对 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

标签: pythonpandasdataframegroup-bypandas-groupby

解决方案


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

推荐阅读