技术求助:如何将row[0]内容迁移至rows[1-9]新增列并删除原行
Got it, let's work through this data transformation task. Based on your example, you need to take each group's header row (the one starting with Grid-ref=), prepend its content to every data row in the same group, then remove the original header row. Here's a straightforward Python implementation that handles this:
Step 1: Group Your Data First
First, we need to split your raw data into groups where each group starts with a Grid-ref= row. This works even if your groups have varying numbers of data rows (not just 10):
# Assume your raw data is stored as a list of lists raw_data = [ ['Grid-ref=', '1', '148'], ['3020', '2820', '3040', '2880', '1740', '1360', '980', '990', '1410', '1770', '2580', '2630'], ['3020', '2820', '3040', '2880', '1740', '1360', '980', '990', '1410', '1770', '2580', '2630'], # ... add the rest of your rows here ['Grid-ref=', '1', '311'], ['490', '290', '280', '230', '200', '250', '440', '530', '460', '420', '530', '450'], # ... add the rest of your rows here ] # Split into groups by Grid-ref rows groups = [] current_group = [] for row in raw_data: # Check if this is a header row if row and row[0] == 'Grid-ref=': # Save the current group if it's not empty if current_group: groups.append(current_group) # Start a new group with this header current_group = [row] else: # Add data row to current group current_group.append(row) # Don't forget to add the last group if current_group: groups.append(current_group)
Step 2: Transform Each Group
Next, we'll process each group: take the header content, prepend it to every data row in the group, and collect all transformed rows:
processed_data = [] for group in groups: # Extract the Grid-ref content from the first row of the group grid_ref_content = group[0] # Iterate over all data rows in the group (skip the header row) for data_row in group[1:]: # Prepend Grid-ref content to the data row new_row = grid_ref_content + data_row processed_data.append(new_row)
Step 3: Verify the Output
If you print processed_data, you'll see exactly the transformed format you need: each row starts with the corresponding Grid-ref= values, followed by the original data.
Handling File Input/Output
If your data is stored in a CSV file, you can use Python's built-in csv module to read and write the data:
import csv # Read from input CSV with open('input_data.csv', 'r') as input_file: reader = csv.reader(input_file) raw_data = list(reader) # ... run the grouping and processing code above ... # Write to output CSV with open('output_data.csv', 'w', newline='') as output_file: writer = csv.writer(output_file) writer.writerows(processed_data)
Alternative: Using Pandas (For Larger Datasets)
If you're working with larger datasets, Pandas can make this even cleaner. Here's a quick version:
import pandas as pd # Read data into a DataFrame (assuming no header row in the CSV) df = pd.read_csv('input_data.csv', header=None) # Create a group identifier: fill forward the Grid-ref rows to mark each group df['group_id'] = df.apply(lambda row: '|'.join(row.dropna().astype(str)) if row[0] == 'Grid-ref=' else None, axis=1) df['group_id'] = df['group_id'].ffill() # Split the group_id into separate columns (the Grid-ref content) grid_ref_cols = df['group_id'].str.split('|', expand=True) # Combine Grid-ref columns with original data, then drop group_id and filter out header rows processed_df = pd.concat([grid_ref_cols, df.drop('group_id', axis=1)], axis=1) processed_df = processed_df[processed_df[0] != 'Grid-ref='] # Reset index if needed processed_df = processed_df.reset_index(drop=True) # Save to CSV processed_df.to_csv('output_data.csv', index=False, header=False)
Let me know if you need adjustments for specific edge cases (like missing values, different delimiters, or other data structures)!
内容的提问来源于stack exchange,提问作者Clives-online

