基于条件过滤DataFrame行:剔除第三列含字符及Null值的行
Solution for Filtering DataFrame Rows
Got it, let's solve this filtering problem step by step. Here's how you can keep only the rows where the value column contains valid numeric values (no strings or nulls):
Step 1: Recreate the original DataFrame (for reference)
First, let's align with the data you provided:
import pandas as pd # Your original dataset data = { 'row': [1, 2, 3, 4, 5], 'col': [1, 1, 1, 1, 1], 'value': ['ID', 12, 12, 4, None] } df = pd.DataFrame(data)
Step 2: Apply the filtering logic
We'll use pd.to_numeric to turn non-numeric values into NaN, then drop any rows with NaN in the value column:
# Convert non-numeric entries to NaN, then filter out rows with NaN filtered_df = df[pd.to_numeric(df['value'], errors='coerce').notna()] # Check the result print(filtered_df)
Expected Output
Running the code above will return exactly the rows you're looking for:
row col value 1 2 1 12 2 3 1 12 3 4 1 4
How it works
pd.to_numeric(df['value'], errors='coerce'): This attempts to convert every entry in thevaluecolumn to a numeric type. Any entries that can't be converted (like the string "ID") or are already null get transformed intoNaN..notna(): Generates a boolean mask whereTrueindicates the value is notNaN.- Using this mask to index the original DataFrame retains only the rows we need.
内容的提问来源于stack exchange,提问作者imran p
相关产品推荐
相关产品推荐

