You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于条件过滤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 the value column to a numeric type. Any entries that can't be converted (like the string "ID") or are already null get transformed into NaN.
  • .notna(): Generates a boolean mask where True indicates the value is not NaN.
  • Using this mask to index the original DataFrame retains only the rows we need.

内容的提问来源于stack exchange,提问作者imran p

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 07:52:27