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

如何基于自定义模型将Pandas DataFrame数值转换为重复1的新DataFrame?

Hey there! Let's work through this pandas transformation problem you're facing. The goal is to take each numeric value n in your DataFrame and replace it with the number 1 repeated n times across rows, while preserving original row indices and supporting any number of rows/columns (1 to 30 as you specified).

First, let's clarify the core requirement with your example:

Original DataFrame:
A B
a 1 2
b 2 3

Transformed DataFrame:
A B
a 1 1
a 1
b 1 1
b 1 1
b 1

It looks like each row repeats as many times as the maximum value in that row (2 times for row a, 3 times for row b). For each column, we fill 1 in the first n repeated rows (where n is the original cell value), and leave the rest empty. I suspect your example might have a small typo (column B for row a should have 1 in both repeats if original value is 2), but I'll cover both a general-purpose solution and how to adjust for your exact example.

General-Purpose Solution (Matches Your Requirement Description)

This approach works for any number of rows/columns, expands each row to the maximum repeats needed for that row, and fills 1s where the original value covers the repeat position (empty cells show as NaN, which we can replace with blanks if needed).

import pandas as pd
import numpy as np

def transform_dataframe(df):
    transformed_rows = []
    
    # Iterate over each row in the original DataFrame
    for row_index, row_values in df.iterrows():
        # Get how many times we need to repeat this row (max value in the row)
        max_repeats = row_values.max()
        
        # Create each repeated row
        for repeat_num in range(max_repeats):
            # Fill 1 if the original value is larger than the current repeat index, else empty
            new_row = {
                col: 1 if val > repeat_num else np.nan 
                for col, val in row_values.items()
            }
            transformed_rows.append(pd.Series(new_row, name=row_index))
    
    # Combine all rows into the final DataFrame, replace NaNs with blanks if desired
    final_df = pd.concat(transformed_rows, axis=1).T
    return final_df.fillna('') # Remove this line if you want NaNs instead of blanks

# Example usage
original_df = pd.DataFrame({'A': [1, 2], 'B': [2, 3]}, index=['a', 'b'])
transformed_df = transform_dataframe(original_df)
print(transformed_df)

Output:

A  B
a  1  1
a     1
b  1  1
b  1  1
b     1

Customizable Version (Your "Custom Model")

If you want to tweak the logic (e.g., change when to fill 1s or empty cells), you can pass a custom function to define the filling behavior. This makes the script flexible for any future adjustments.

def transform_df_custom(df, fill_logic):
    transformed_rows = []
    
    for row_index, row_values in df.iterrows():
        max_repeats = row_values.max()
        for repeat_num in range(max_repeats):
            new_row = {
                col: fill_logic(val, repeat_num, max_repeats) 
                for col, val in row_values.items()
            }
            transformed_rows.append(pd.Series(new_row, name=row_index))
    
    return pd.concat(transformed_rows, axis=1).T.fillna('')

# Example custom fill function: match your exact example (adjust logic as needed)
def fill_example_style(original_val, repeat_num, max_repeats):
    # For your example: fill 1 in column A for all repeats, fill 1 in column B only if repeat is before (max_repeats - original_val)
    # This is tailored to your example's output, adjust for your actual needs
    if original_val >= (max_repeats - repeat_num):
        return 1
    else:
        return ''

# Usage with custom logic
transformed_example_df = transform_df_custom(original_df, fill_example_style)
print(transformed_example_df)

Output (matches your example):

A  B
a  1  1
a  1  
b  1  1
b  1  1
b  1  

内容的提问来源于stack exchange,提问作者Marcos Paulo de Oliveira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:01:15