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

如何筛选pandas DataFrame中point列值为字符串类型的行?

筛选pandas DataFrame中指定列值为字符串类型的行

核心问题

你的point列是混合数值与字符串的object类型列,整列的dtype无法反映单个元素的类型,因此直接用整列dtype判断或select_dtypes方法都不适用,需要逐元素检查类型。

可行解法

方法1:逐元素判断类型(基础版)

先构造示例数据,再通过apply遍历point列的每个元素,判断其类型是否为字符串:

import pandas as pd

# 构造示例DataFrame
data = {
    'id': [0, 1, 2, 3, 4],
    'name': ['x', 'y', 'z', 't', 'q'],
    'point': [5, 6, 'ten', 'nine', 'two']
}
df = pd.DataFrame(data)

# 筛选point值为字符串的行
str_filtered_df = df[df['point'].apply(lambda x: type(x) is str)]
print(str_filtered_df)

输出结果:

idnamepoint
2zten
3tnine
4qtwo

方法2:使用pandas内置类型检查(更严谨)

如果需要兼容字符串子类的情况,推荐用pandas提供的is_string函数:

str_filtered_df = df[df['point'].apply(pd.api.types.is_string)]

为什么你的尝试失败?

  • df[df['point'].dtype == str]:df['point'].dtype返回的是整列的数据类型(此处为object),不是单个元素的类型,因此该条件无法筛选目标行。
  • select_dtypes:此方法用于筛选整个列的数据类型,而非行中单个元素的类型,不符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:25:48