如何优雅优化Pandas循环中带编号命名的统计新列创建代码
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_coltypo) or manual counter management. - Scalability: Want to add a new metric like median? Just add
"median": "median"tostats_mapping. Need a new column segment? Add a tuple toslice_ranges. - Readability: The code clearly expresses intent—anyone reading it can quickly see what segments and metrics are being processed.
内容的提问来源于stack exchange,提问作者Reut

