如何筛选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)
输出结果:
| id | name | point |
|---|---|---|
| 2 | z | ten |
| 3 | t | nine |
| 4 | q | two |
方法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
相关产品推荐
相关产品推荐

