如何使用Python的pandas库编辑.csv文件(添加行与删除行)
Hey there! Let's work through your CSV manipulation tasks with Python— I'll walk you through each requirement with practical, easy-to-use code snippets. Let's dive in!
1. Remove Top or Bottom 10 Rows
First, we'll prompt you to choose whether to trim from the top or bottom, then modify the CSV accordingly. I'll cover two approaches: using Python's built-in csv module (no external installs needed) and pandas (great for larger files and simpler syntax).
Using the Built-in csv Module
import csv # Get user choice for which rows to remove remove_choice = input("Do you want to remove the TOP 10 rows or BOTTOM 10 rows? Enter 'top' or 'bottom': ").lower() # Read all rows from the original CSV with open('your_file.csv', 'r', newline='') as infile: all_rows = list(csv.reader(infile)) # Process rows based on user choice if remove_choice == 'top': modified_rows = all_rows[10:] # Skip first 10 rows elif remove_choice == 'bottom': modified_rows = all_rows[:-10] # Exclude last 10 rows else: print("Oops! Invalid choice— please enter 'top' or 'bottom'.") exit() # Write the modified data to a new CSV (or overwrite the original if you prefer) with open('trimmed_file.csv', 'w', newline='') as outfile: writer = csv.writer(outfile) writer.writerows(modified_rows) print(f"Success! Removed the {remove_choice} 10 rows. Check out trimmed_file.csv.")
Using pandas (Shorter Syntax)
If you have pandas installed (pip install pandas if not), this is a quicker option:
import pandas as pd remove_choice = input("Remove TOP or BOTTOM 10 rows? Enter 'top'/'bottom': ").lower() # Load the CSV into a DataFrame df = pd.read_csv('your_file.csv') # Trim rows based on choice if remove_choice == 'top': df_trimmed = df.iloc[10:] elif remove_choice == 'bottom': df_trimmed = df.iloc[:-10] else: print("Invalid choice! Please try again.") exit() # Save the trimmed DataFrame to CSV df_trimmed.to_csv('trimmed_file.csv', index=False) print(f"Done! {remove_choice} 10 rows removed successfully.")
2. Add 10 Rows to the Top & Input Their Data
Next, we'll collect your input for each of the 10 new rows, then prepend them to your CSV. Again, I'll cover both csv and pandas methods, including handling cases where your CSV has column headers.
Using the Built-in csv Module
import csv # First, read the original CSV with open('your_file.csv', 'r', newline='') as infile: reader = csv.reader(infile) # Check if the CSV has headers has_headers = input("Does your CSV have column headers? Enter 'yes' or 'no': ").lower() if has_headers == 'yes': headers = next(reader) original_data = list(reader) else: headers = None original_data = list(reader) # Collect data for 10 new rows new_rows = [] column_count = len(headers) if headers else len(original_data[0]) if original_data else 0 print(f"\nEnter data for each of the 10 new rows (separate values with commas— {column_count} values per row):") for row_num in range(1, 11): while True: user_input = input(f"Row {row_num}: ") row_values = [val.strip() for val in user_input.split(',')] # Validate the number of values matches the CSV's columns if len(row_values) == column_count: new_rows.append(row_values) break else: print(f"Whoops! Please enter exactly {column_count} values (matching the CSV's columns).") # Combine new rows with original data (account for headers) if has_headers == 'yes': header_placement = input("\nAdd new rows ABOVE headers or BELOW headers? Enter 'above' or 'below': ").lower() if header_placement == 'above': full_data = new_rows + [headers] + original_data else: full_data = [headers] + new_rows + original_data else: full_data = new_rows + original_data # Write the combined data to a new CSV with open('file_with_new_rows.csv', 'w', newline='') as outfile: writer = csv.writer(outfile) writer.writerows(full_data) print("\n10 new rows added successfully! Check file_with_new_rows.csv.")
Using pandas
import pandas as pd # Load the original CSV df = pd.read_csv('your_file.csv') columns = df.columns.tolist() # Collect data for 10 new rows new_rows_data = [] print(f"Enter data for 10 new rows (each row needs {len(columns)} values, separated by commas):") for row_num in range(1, 11): while True: user_input = input(f"Row {row_num}: ") row_values = [val.strip() for val in user_input.split(',')] if len(row_values) == len(columns): # Create a dictionary matching column names to values row_dict = dict(zip(columns, row_values)) new_rows_data.append(row_dict) break else: print(f"Please enter exactly {len(columns)} values— one for each column.") # Create a new DataFrame for the new rows new_df = pd.DataFrame(new_rows_data, columns=columns) # Prepend the new rows to the original DataFrame combined_df = pd.concat([new_df, df], ignore_index=True) # Save to CSV combined_df.to_csv('file_with_new_rows.csv', index=False) print("Success! 10 rows added to the top of your CSV.")
Quick Tips
- Replace
'your_file.csv'with your actual file path (e.g.,'C:/data/my_csv.csv'on Windows or'/home/user/data/my_csv.csv'on Linux/macOS). - If your CSV uses a delimiter other than commas (like tabs), add
delimiter='\t'tocsv.reader/csv.writerorpd.read_csv(). - Always make a backup of your original CSV before modifying it— better safe than sorry!
内容的提问来源于stack exchange,提问作者codekage

