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

如何优雅优化Pandas循环中带编号命名的统计新列创建代码

Optimizing Your Pandas Statistical Calculation Code

Nice job getting the original script working! Let’s clean this up to make it more maintainable, concise, and less prone to typos (like the kurt_col mistakenly using mean_ in your original code). Here’s a streamlined approach:

Step 1: Centralize Your Slice Ranges

Instead of manually creating each phen_* DataFrame, store your column ranges in a list. This makes it easy to adjust ranges or add new segments later:

# Define all column slice ranges in one place
slice_ranges = [(0, 20), (20, 55), (55, 70), (70, 80), (70, 110)]

Step 2: Use a Dictionary for Statistical Metrics

Map the names you want for your new columns to the corresponding Pandas methods. This eliminates repetitive code and makes adding new metrics trivial:

# Map desired column prefixes to Pandas row-wise methods
stats_mapping = {
    "mean": "mean",
    "std": "std",
    "skew": "skew",
    "kurt": "kurt",
    "total": "sum"
}

Step 3: Streamline the Loop with enumerate

Use enumerate to automatically track your phen number (starting at 1) instead of manually incrementing a variable. Combine this with the above mappings to generate all columns cleanly:

for phen_num, (start, end) in enumerate(slice_ranges, start=1):
    # Extract the current segment of rain_calc
    sub_df = rain_calc.iloc[:, start:end]
    # Calculate each metric and add to original_df
    for stat_name, method in stats_mapping.items():
        col_name = f"{stat_name}_{phen_num}"
        original_df[col_name] = getattr(sub_df, method)(axis=1)

Why This Works Better

  • Maintainability: All slice ranges and metrics are in one place—no need to hunt through code to adjust values or add new calculations.
  • Error Reduction: No more manual string concatenation for column names (which caused your kurt_col typo) or manual counter management.
  • Scalability: Want to add a new metric like median? Just add "median": "median" to stats_mapping. Need a new column segment? Add a tuple to slice_ranges.
  • Readability: The code clearly expresses intent—anyone reading it can quickly see what segments and metrics are being processed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:28:10