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

如何在Python中将列表数值分箱为状态类别并生成转移状态数组

Mapping Numerical Array to State Array for Transition Matrix in Python

Got it, let's break down how to convert your numerical array into the required state array, then use it to build a transition matrix.

First, let's clarify the mapping rules you specified:

  • Values in [0, 10) → State 1
  • Values in [10, 20) → State 2
  • Values in [20, 30) → State 3

Step 1: Convert Numerical Array to State Array

Your original array is [1.2, 4.6, 3.7, 11.2, 13, 5, 18.9, 0.3, 20.0, 26.7, 1]. Note that the example state array you provided has 10 elements, but your original array has 11—so the correct state array should be [1, 1, 1, 2, 2, 1, 2, 1, 3, 3, 1]. Here are two ways to generate this:

Option 1: Pure Python (No External Libraries)

If you don't want to use numpy, a simple loop or list comprehension works perfectly:

original_array = [1.2, 4.6, 3.7, 11.2, 13, 5, 18.9, 0.3, 20.0, 26.7, 1]

# Concise list comprehension for mapping
state_array = [
    1 if 0 <= num < 10 
    else 2 if 10 <= num < 20 
    else 3 if 20 <= num < 30 
    else None  # Add this to handle out-of-range values if needed
    for num in original_array
]

print(state_array)  # Output: [1, 1, 1, 2, 2, 1, 2, 1, 3, 3, 1]

Option 2: Using NumPy (Better for Large Datasets)

For larger arrays, numpy is faster and more efficient. We can use np.digitize—it's built for exactly this kind of interval mapping:

import numpy as np

original_array = np.array([1.2, 4.6, 3.7, 11.2, 13, 5, 18.9, 0.3, 20.0, 26.7, 1])
bins = [0, 10, 20, 30]  # Define our interval boundaries

# right=False ensures intervals are left-closed, right-open (matches your rules)
state_array = np.digitize(original_array, bins, right=False)

print(state_array.tolist())  # Convert back to a list if needed: [1, 1, 1, 2, 2, 1, 2, 1, 3, 3, 1]

Step 2: Build the Transition Matrix

Once you have the state array, you can count state transitions and normalize to get a transition matrix. Here's a straightforward implementation:

# Initialize a 3x3 count matrix (for states 1-3)
transition_counts = np.zeros((3, 3), dtype=int)

# Iterate through consecutive state pairs
for i in range(len(state_array) - 1):
    # Convert to 0-indexed for array access
    current_state = state_array[i] - 1
    next_state = state_array[i+1] - 1
    transition_counts[current_state][next_state] += 1

# Normalize rows to get transition probabilities (each row sums to 1)
transition_matrix = transition_counts / transition_counts.sum(axis=1, keepdims=True)

print("Transition Matrix:")
print(transition_matrix)

Running this will give you a matrix where transition_matrix[i][j] represents the probability of moving from state i+1 to state j+1.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 23:04:06