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

二维数组透视分组计数:按Step统计Status的计数与求和

Solution for 2D Array Pivoting, Counting & Step-Specific Status Stats

Hey there! Let's walk through how to solve your 2D array processing requirements with practical examples (we'll use Python and JavaScript since they're common for this type of task).

1. Pivot the 2D Array & Create a New Array with Zero-Default Columns

First, we need to group data by user, track counts for every combination of Step (1-4) and Status, and fill in zeros where there's no data for a user-step-status trio.

Example Input Structure

Let's assume your original array looks like this (each entry = [User ID, Step, Status]):

original_data = [
    [1, 1, "completed"],
    [1, 2, "completed"],
    [2, 1, "pending"],
    [3, 3, "completed"],
    [2, 2, "failed"],
    [3, 1, "completed"],
]

Python Implementation

from collections import defaultdict

# Extract unique users, all required steps (1-4), and unique statuses
users = sorted({row[0] for row in original_data})
steps = list(range(1, 5))
statuses = sorted({row[2] for row in original_data})

# Initialize pivot table with zero defaults
pivot_table = defaultdict(lambda: defaultdict(int))
for user in users:
    for step in steps:
        for status in statuses:
            pivot_table[user][(step, status)] = 0

# Populate counts from original data
for row in original_data:
    user, step, status = row
    pivot_table[user][(step, status)] += 1

# Convert to final 2D array with headers
header = ["User ID"] + [f"Step {step} - {status}" for step in steps for status in statuses]
final_array = [header]
for user in users:
    row = [user]
    for step in steps:
        for status in statuses:
            row.append(pivot_table[user][(step, status)])
    final_array.append(row)

# Output result
print("Final 2D Array:")
for row in final_array:
    print(row)

JavaScript Implementation

const originalData = [
    [1, 1, "completed"],
    [1, 2, "completed"],
    [2, 1, "pending"],
    [3, 3, "completed"],
    [2, 2, "failed"],
    [3, 1, "completed"],
];

// Extract unique values
const users = [...new Set(originalData.map(row => row[0]))].sort();
const steps = [1, 2, 3, 4];
const statuses = [...new Set(originalData.map(row => row[2]))].sort();

// Initialize pivot table with zeros
const pivotTable = {};
users.forEach(user => {
    pivotTable[user] = {};
    steps.forEach(step => {
        statuses.forEach(status => {
            pivotTable[user][`Step${step}-${status}`] = 0;
        });
    });
});

// Fill in counts
originalData.forEach(row => {
    const [user, step, status] = row;
    pivotTable[user][`Step${step}-${status}`]++;
});

// Build final 2D array
const header = ["User ID", ...steps.flatMap(step => statuses.map(status => `Step ${step} - ${status}`))];
const finalArray = [header];
users.forEach(user => {
    const row = [user];
    steps.forEach(step => {
        statuses.forEach(status => {
            row.push(pivotTable[user][`Step${step}-${status}`]);
        });
    });
    finalArray.push(row);
});

// Output result
console.log("Final 2D Array:");
console.table(finalArray);

2. Count & Sum Statuses for a Specific Step

Next, we'll create a function to tally up all Status counts for a given Step, plus calculate the total number of entries for that Step.

Python Implementation

def get_step_status_stats(target_step, data):
    status_counts = defaultdict(int)
    total_entries = 0
    for row in data:
        if row[1] == target_step:
            status = row[2]
            status_counts[status] += 1
            total_entries += 1
    return dict(status_counts), total_entries

# Example: Get stats for Step 1
step_1_counts, step_1_total = get_step_status_stats(1, original_data)
print(f"\nStep 1 Status Counts: {step_1_counts}")
print(f"Step 1 Total Entries: {step_1_total}")

JavaScript Implementation

function getStepStatusStats(targetStep, data) {
    const statusCounts = {};
    let totalEntries = 0;
    data.forEach(row => {
        if (row[1] === targetStep) {
            const status = row[2];
            statusCounts[status] = (statusCounts[status] || 0) + 1;
            totalEntries++;
        }
    });
    return { statusCounts, totalEntries };
}

// Example: Get stats for Step 1
const { statusCounts: step1Counts, totalEntries: step1Total } = getStepStatusStats(1, originalData);
console.log("\nStep 1 Status Counts:", step1Counts);
console.log("Step 1 Total Entries:", step1Total);

Key Notes

  • The solutions handle variable user counts (1 to N) and fixed Step range (1-4) as required.
  • Zero defaults ensure no gaps in the final array, even if a user has no data for a specific Step or Status.
  • The status counting function works for any target Step (just pass 1, 2, 3, or 4 as needed).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:38:19