R语言中批量修改wheat_cities数据框列名的技术求助
Solution for Renaming Columns in wheat_cities DataFrame
Got it, let's work through this column renaming task together. Since fixed-length substring methods won't work here, we'll use string splitting tailored to each column's position. Here's a practical pandas-based solution:
import pandas as pd # Convert column names to a list for easy manipulation column_list = wheat_cities.columns.tolist() new_column_names = [] # Iterate through each column with its index to target specific columns for idx, col_name in enumerate(column_list): if idx == 0: # Keep the "Date" column as-is new_column_names.append(col_name) elif 1 <= idx <= 2: # For columns 2 and 3 (0-indexed 1 and 2): keep content after first ".." split_parts = col_name.split('..') # Grab everything after the first occurrence of ".." (fallback to original if no separator) new_name = split_parts[1] if len(split_parts) > 1 else col_name new_column_names.append(new_name) elif 4 <= idx <= 75: # For columns 5 to 76 (0-indexed 4 to 75): keep content after second ".." # Limit split to 3 parts to avoid over-splitting if more ".." exist split_parts = col_name.split('..', 3) # Grab everything after the second occurrence of ".." (fallback to original if not enough separators) new_name = split_parts[2] if len(split_parts) > 2 else col_name new_column_names.append(new_name) else: # Keep column 4 (0-indexed 3) unchanged as no instruction was given new_column_names.append(col_name) # Assign the new column names back to the DataFrame wheat_cities.columns = new_column_names
Key Details:
- Index Alignment: The code uses pandas' standard 0-based indexing to match your request:
- Columns 2 & 3 → indexes 1 & 2
- Columns 5 to 76 → indexes 4 to 75
- Error Prevention: We added fallback logic to retain the original column name if it doesn't have enough ".." separators—this avoids crashes from unexpected column name formats.
- Clean Splitting: For columns needing content after the second "..",
split('..', 3)ensures we only split up to the third part, so any extra ".." later in the name stay intact in the final column name.
内容的提问来源于stack exchange,提问作者Sankalp Mathur
相关产品推荐
相关产品推荐

