如何用Pandas筛选Primary列值为Germany的行并导出至Excel?
No worries at all—everyone starts somewhere! Let's get your data filtered and exported step by step, building on the work you've already done.
First, you've nailed the foundational steps: importing libraries, setting your working directory, loading the Excel file, and confirming your column names. Perfect start!
Step 1: Filter Rows for "Germany" in the Primary Column
Add this line right after you load your DataFrame (df=pd.read_excel(...)):
# Create a new DataFrame with only rows where Primary equals "Germany" filtered_df = df[df['Primary'] == 'Germany']
This line checks every row in your original DataFrame, keeps only those where the Primary column has the exact value "Germany", and stores the result in filtered_df.
Step 2: Export the Filtered Data to Excel
Next, use Pandas' built-in to_excel() method to save your filtered results. Add this code:
# Export the filtered data to a new Excel file filtered_df.to_excel('germany_filtered_data.xlsx', index=False)
'germany_filtered_data.xlsx'is the name of your output file (feel free to rename it to something that makes sense for your project).index=Falsetells Pandas not to add an extra column for the row index in the Excel file—this keeps your output clean and matches the structure of your original data.
Full Complete Code
Here's the full, polished code (note I added import os since you're using os.chdir()—it was missing from your original steps!):
import pandas as pd import numpy as np import os # Required for changing the working directory # Set your working directory os.chdir('C:\\Users\\Desktop') # Load the Excel file df = pd.read_excel('test2.xlsx', sheet_name="Sheet1", header=4) # Filter rows where Primary is "Germany" filtered_df = df[df['Primary'] == 'Germany'] # Export the filtered results to Excel filtered_df.to_excel('germany_filtered_data.xlsx', index=False)
Optional: Verify Your Results
If you want to double-check the filtered data before exporting, add these lines to print a preview:
# Print the first 5 rows of the filtered data print(filtered_df.head()) # Print how many rows were kept print(f"Total rows with Primary = 'Germany': {len(filtered_df)}")
Once you run the full code, you'll find a new Excel file in your Desktop folder with exactly the rows you need.
内容的提问来源于stack exchange,提问作者Saad Sohail

