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 ofColumn1andColumn2occurs. For example, if 15 rows haveColumn1 = 'C'andColumn2 = '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
相关产品推荐
相关产品推荐

