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

Python中DataFrame内两个列表元素的运算实现问题

Solution for Calculating Corresponding Column Differences Between Two Lists in Pandas

Got it, let's break down how to solve this problem cleanly. You want to subtract each element in ListA from the corresponding element in ListB, then add those results as new columns to your Output DataFrame. Here are a few practical methods, from beginner-friendly to pandas-optimized:

Method 1: Simple Loop (Easy to Understand)

This method is great if you're still getting comfortable with pandas, since it's explicit and easy to trace:

import pandas as pd

# Your input lists (adjust variable names as needed)
ListA = ["In_3M", "Out_3M", "Go_3M"]
ListB = ["In_6M", "Out_6M", "Go_6M"]

# Assume your input DataFrame is named input_df
output_df = input_df.copy()  # Create a copy to avoid modifying the original data

# Loop through corresponding pairs of columns
for col_a, col_b in zip(ListA, ListB):
    # Define a meaningful name for the new column (customize this!)
    new_col_name = f"{col_b}_minus_{col_a}"
    # Calculate the difference and add to output_df
    output_df[new_col_name] = input_df[col_b] - input_df[col_a]

Method 2: Vectorized Operation (Most Efficient)

Pandas is built for vectorized operations—this method skips loops entirely and is way faster for large datasets:

import pandas as pd

ListA = ["In_3M", "Out_3M", "Go_3M"]
ListB = ["In_6M", "Out_6M", "Go_6M"]

# Example input data (replace with your actual data)
input_df = pd.DataFrame(
    {"In_3M": [10, 20, 30], "Out_3M": [5, 15, 25], "Go_3M": [2, 4, 6],
     "In_6M": [15, 25, 35], "Out_6M": [8, 18, 28], "Go_6M": [3, 5, 7]}
)

# Create new columns in one go using vectorized subtraction
new_cols = [f"{b}_minus_{a}" for a, b in zip(ListA, ListB)]
output_df = input_df.assign(**dict(zip(new_cols, input_df[ListB].values - input_df[ListA].values)))

# Print to verify results
print(output_df)

This will generate columns like In_6M_minus_In_3M with the correct difference values.

Method 3: List Comprehension (Concise)

If you prefer tight, readable code, a list comprehension can handle the column additions in one line:

output_df = input_df.copy()
[output_df.update({f"{b}_minus_{a}": input_df[b] - input_df[a]}) for a, b in zip(ListA, ListB)]

Key Notes:

  • Always use copy() when creating your Output DataFrame unless you intentionally want to modify the original Input DF.
  • Customize the new column names to fit your workflow—you could use shorter names like In_Diff instead of the verbose version if that's better.
  • Ensure all corresponding columns in ListA and ListB are numeric (int/float); if not, convert them first with pd.to_numeric(input_df[col], errors="coerce").

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:45:50