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

如何在Pandas中指定位置批量添加列?为多组S/L列对插入比率列并终止于字符串列前

Solution for Batch Calculating and Inserting Ratio Columns in Pandas DataFrame

Got it, let's work through this problem step by step. Instead of melting the DataFrame (which complicates keeping column groups intact), we can directly manipulate column positions and calculate ratios in place. Here's a clean, efficient approach:

Full Working Code

import pandas as pd

# Your original DataFrame
df = pd.DataFrame({
    'FS': [1,1,2],
    'FL': [2,3,4],
    'GS': [5,8,9],
    'GL': [5,2,4],
    'JJ': ['no','more','math']
})

# 1. Find the position of the 'JJ' column to know where to stop processing
jj_col_index = df.columns.get_loc('JJ')

# 2. Extract all column groups (prefixes) from columns ending with 'S' (before JJ)
s_columns = [col for col in df.columns[:jj_col_index] if col.endswith('S')]
group_prefixes = [col[:-1] for col in s_columns]  # e.g., 'FS' becomes 'F'

# 3. Loop through each group to calculate and insert ratio columns
for prefix in group_prefixes:
    s_col = f"{prefix}S"
    l_col = f"{prefix}L"
    ratio_col_name = f"{prefix}Ratio"
    
    # Calculate ratio with 3 decimal places (matches your expected output)
    df[ratio_col_name] = (df[s_col] / (df[s_col] + df[l_col])).round(3)
    
    # Insert the ratio column right after the corresponding 'L' column
    l_col_index = df.columns.get_loc(l_col)
    # Pop the ratio column from the end and insert at the correct position
    df.insert(l_col_index + 1, ratio_col_name, df.pop(ratio_col_name))

# Check the result
print(df)

Output

FS  FL  FRatio  GS  GL  GRatio    JJ
0   1   2   0.333   5   5    0.500    no
1   1   3   0.250   8   2    0.800  more
2   2   4   0.333   9   4    0.692  math

How This Works

Let's break down the key steps:

  • Locate the stop point: We use df.columns.get_loc('JJ') to find the index of the 'JJ' column, so we only process columns that come before it and leave the string column untouched.
  • Identify column groups: By filtering columns ending with 'S' (the start of each pair), we extract the shared prefix (like 'F' for FS/FL). This ensures we pair each 'S' column with its corresponding 'L' column correctly, even with 64 columns.
  • Calculate and insert ratios:
    • For each group, we compute the ratio using your formula S/(S+L), rounding to 3 decimals to match your expected output.
    • We find the position of the 'L' column, then insert the new ratio column immediately after it using df.insert(). Using df.pop() moves the ratio column from the end of the DataFrame to the desired position without duplicating data.

This approach keeps your original column structure intact, avoids unnecessary data reshaping, and scales seamlessly to your 64-column DataFrame—just ensure all S/L pairs follow the same prefix-S/prefix-L naming pattern.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 18:27:35