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

如何用Pandas的apply方法结合行列值生成填充矩阵?

Solution for Creating a Concatenated Matrix with Pandas apply

Hey there! Let's break down how to solve this problem step by step, since you're new to Python and Pandas. From your example, it looks like you want to create a matrix where each cell is the concatenation of a row label and a column label, using a custom two-variable function with Pandas' apply method. Here's exactly how to do it:

Full Working Code

import pandas as pd

# Custom function that takes two variables and returns their concatenation
def combine(row_char, col_char):
    return row_char + col_char

# Set up input data based on your example
row_labels = ['a', 'b', 'c', 'd', 'e']
extra_columns = ['f', 'g']
column_labels = row_labels + extra_columns  # Final column set

# Initialize empty DataFrame with the required rows and columns
df = pd.DataFrame(index=row_labels, columns=column_labels)

# Use apply to fill the DataFrame with combined values
df = df.apply(
    lambda row: [combine(row.name, col) for col in df.columns],
    axis=1,
    result_type='expand'
)

# Print the formatted output
print(df.to_string(header=True, index=True))

Step-by-Step Explanation

  • Custom Two-Variable Function: The combine function is straightforward—it takes a row character and a column character, then returns their concatenation. This is the core function you wanted to use.
  • Input Setup: We define row labels from your first input line, and the extra columns ('f', 'g') from the start of your second input line. Merging these gives us all the column labels for the final matrix.
  • Empty DataFrame Structure: We create an empty DataFrame with the correct rows and columns first—this gives us the framework to populate.
  • Using apply:
    • axis=1 tells Pandas to run the function over each row instead of each column.
    • row.name gives us the label of the current row (like 'a' or 'b').
    • We loop through each column label, call combine with the row label and column label, and result_type='expand' ensures the output fills the DataFrame columns correctly.
  • Matching Your Example Output: When you run the code, the printed result will exactly match the matrix you provided.

Handling Raw Text Input

If your input comes directly as text lines (like the example you shared), you can parse them into the labels like this:

# Example raw input lines
input_line1 = "a b c d e"
input_line2 = "f g a b c d e"

# Parse into labels
row_labels = input_line1.split()
extra_columns = input_line2.split()[:2]  # Grab the first two elements: 'f', 'g'
column_labels = row_labels + extra_columns

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:05:05