You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python按自定义边界拆分Numpy数组?

Got it, let's work through this problem step by step. You've got two core tasks here: first identifying the segment boundaries from your 49x64 reference array, then using those boundaries to extract the corresponding segments from your 3031x64 binary array. Here's a practical, numpy-based solution tailored to your needs:

1. Detect Segment Boundaries from the Reference Array

First, we need to pinpoint where each segment starts and ends in your reference array. Based on your example, segments are defined by value changes in a row. We'll assume either:

  • All rows in the reference array follow the same segment pattern (so we can use a single row to extract boundaries), or
  • You need to find boundaries common to all rows (we'll cover both cases).

Case 1: All rows share the same segment pattern

Use the first row of your reference array to detect boundaries (since it's representative):

import numpy as np

# Replace with your actual 49x64 reference array
ref_array = np.load("your_reference_array.npy")

# Grab the first row to analyze segment changes
reference_row = ref_array[0]

# Find indices where the value changes (shift by 1 to get the start of the new segment)
change_points = np.where(reference_row[:-1] != reference_row[1:])[0] + 1

# Combine start (0), change points, and end (64) to get full segment boundaries
segment_boundaries = np.concatenate([[0], change_points, [reference_row.shape[0]]])

# Convert boundaries to (start, end) tuples for easy extraction
segments = [(segment_boundaries[i], segment_boundaries[i+1]) for i in range(len(segment_boundaries)-1)]

For your example row [1,1,0,0,2,2,2,2,...], this would generate segments like [(0,2), (2,4), (4,8), ...].

Case 2: Find boundaries common to all rows

If rows have slight variations but you need universal boundaries, calculate the intersection of change points across all rows:

# Collect change points for every row in the reference array
all_change_points = []
for row in ref_array:
    cp = np.where(row[:-1] != row[1:])[0] + 1
    all_change_points.append(cp)

# Find change points that exist in every row
common_change_points = np.intersect1d(*all_change_points)

# Build universal segment boundaries
segment_boundaries = np.concatenate([[0], common_change_points, [64]])
segments = [(segment_boundaries[i], segment_boundaries[i+1]) for i in range(len(segment_boundaries)-1)]

2. Extract Segments from the Binary Array

Now apply the segments list to your 3031x64 binary array. You can extract raw subarrays or format them into the string-like output you showed (e.g., [[11], [10], ...]):

Option 1: Extract raw binary subarrays

This keeps the segment data as numpy arrays (useful for further processing):

# Replace with your actual 3031x64 binary array
binary_array = np.load("your_binary_array.npy")

extracted_segments = []
for start, end in segments:
    # Extract all rows from columns start to end
    segment_data = binary_array[:, start:end]
    extracted_segments.append(segment_data)

# Example: extracted_segments[0] is your 3031x2 array of the first segment

Option 2: Format into string-style output

If you need the segments as concatenated strings (like [11] or [01]):

extracted_segment_strings = []
for start, end in segments:
    # Extract the segment
    segment_data = binary_array[:, start:end]
    # Convert each row's binary values to a string
    row_strings = np.apply_along_axis(lambda x: ''.join(map(str, x)), 1, segment_data)
    # Reshape to match your desired [[str], [str], ...] format
    extracted_segment_strings.append(row_strings.reshape(-1, 1))

# Example: extracted_segment_strings[0] gives your first segment output

Full Example with Sample Data

Here's a minimal working example to test the logic:

import numpy as np

# Mock reference array (49x8 for brevity)
ref_array = np.tile([1,1,0,0,2,2,2,2], (49, 1))

# Mock binary array (10x8 for brevity)
binary_array = np.random.randint(0, 2, size=(10, 8))

# Step 1: Get segment boundaries
reference_row = ref_array[0]
change_points = np.where(reference_row[:-1] != reference_row[1:])[0] + 1
segment_boundaries = np.concatenate([[0], change_points, [8]])
segments = [(segment_boundaries[i], segment_boundaries[i+1]) for i in range(len(segment_boundaries)-1)]

# Step 2: Extract formatted segments
extracted = []
for start, end in segments:
    seg_data = binary_array[:, start:end]
    seg_str = np.apply_along_axis(lambda x: ''.join(map(str, x)), 1, seg_data)
    extracted.append(seg_str.reshape(-1,1))

# Print first segment output
print("First segment output:")
print(extracted[0])

Notes

  • If your reference array rows have unique segment patterns (and binary array rows map 1:1 to reference rows), loop through each pair of reference row and binary row to extract row-specific segments.
  • Adjust the boundary logic if your segments are defined by more complex rules (e.g., threshold values instead of exact value changes).

内容的提问来源于stack exchange,提问作者Federico_Lorenzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:47:36