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

Python新手求助:如何从CSV生成字符串转换矩阵并统计对应行数

How to Create a Transition Matrix from CSV Columns in Python

Hey there! Since you're new to Python, let's break this down step by step to build that transition matrix you need. We'll use pandas—a super handy library for working with tabular data like CSVs—it'll make this task way simpler.

Step 1: Install Pandas (if you haven't already)

First, make sure you have pandas installed. Open your terminal/command prompt and run:

pip install pandas

Step 2: Load Your CSV and Generate the Transition Matrix

Here's a complete script with comments to walk you through it:

import pandas as pd

# 1. Read your CSV file
# Replace 'your_file.csv' with the actual path to your CSV
df = pd.read_csv('your_file.csv')

# 2. Define the list of possible values (keep this order consistent for your matrix rows/columns)
possible_values = ['C', 'CD', 'D', 'N', 'S', 'SN']

# 3. Create the transition matrix using pandas' crosstab function
# This counts how many times each (Column1, Column2) pair occurs
transition_matrix = pd.crosstab(df['Column1'], df['Column2'], rownames=['From'], colnames=['To'])

# 4. Reindex to ensure all possible values are included (in case some pairs don't exist in your data)
transition_matrix = transition_matrix.reindex(index=possible_values, columns=possible_values, fill_value=0)

# 5. Print or save the matrix
print("Transition Matrix (count of each conversion):")
print(transition_matrix)

# Optional: Save the matrix to a new CSV if you need it
transition_matrix.to_csv('transition_matrix.csv')

What This Does:

  • pd.crosstab() automatically counts the number of rows where each combination of Column1 and Column2 occurs. For example, if 15 rows have Column1 = 'C' and Column2 = 'D', the cell at row 'C' and column 'D' will be 15.
  • reindex() makes sure even if some value pairs don't appear in your data (like 'SN' to 'C'), they still show up in the matrix with a 0 instead of being missing.

Example Output:

If your data has a few conversions, your matrix might look like this:

To    C  CD  D  N  S  SN
From
C     5   2  3  0  1   0
CD    1   4  0  2  0   1
D     0   1  6  1  0   0
N     2   0  1  7  3   2
S     0   0  0  2  5   4
SN    1   0  0  1  2   6

That's it! This should give you exactly the matrix you're looking for, with each cell representing the number of rows that match the corresponding transition.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:15:26