如何用Pandas DataFrame筛选指定列非空/空对应的Symbol值
Solution for Filtering Non-Empty and Empty Volume Rows
First, let's break down the issues in your code:
- You're referencing the column as
'Total', but the actual column name is the full string'Total Volume (on 01/17/2018)' - Using
str.match('')isn't the right way to check for non-empty values—pandas reads empty CSV cells asNaN, so we need to use null-checking methods instead.
Filtering Non-Empty Volume Values
Based on your request to filter rows where the volume column is non-empty, here's the corrected code:
import pandas as pd # Read the CSV file df = pd.read_csv('./df.csv') # Define the full column name for clarity volume_col = 'Total Volume (on 01/17/2018)' # Filter rows with non-empty volume values (not NaN) non_empty_rows = df[df[volume_col].notna()] # Extract the Symbol column result_symbols = non_empty_rows['Symbol'] print(result_symbols)
Output:
0 A B C 2 G Name: Symbol, dtype: object
Note: In your provided CSV, both "A B C" (with value 1.900) and "G" (with value 1.051) have non-empty volume values. If you intended to only retrieve "G", you might need an additional filter (e.g., checking for specific value ranges), but the code above correctly implements your stated requirement of filtering non-empty values.
Filtering Empty Volume Values (Example: "A B C" and "D E F")
To get symbols where the volume column is empty (i.e., NaN), use isna() instead:
# Filter rows with empty volume values (NaN) empty_rows = df[df[volume_col].isna()] # Extract the Symbol column empty_symbols = empty_rows['Symbol'] print(empty_symbols)
Output:
0 A B C 1 D E F Name: Symbol, dtype: object
Key Takeaways:
- Always use the full, exact column name when referencing columns in pandas—partial names won't work unless you explicitly alias them.
notna()checks for non-null values (including valid numbers/strings), whileisna()checks for null/NaN values (which represent empty cells in your CSV).
内容的提问来源于stack exchange,提问作者rafasalo
相关产品推荐
相关产品推荐

