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

Pandas报错'str' object has no attribute 'str':筛选含'tu'列求助

解决Pandas筛选含'tu'列时的'str'属性错误问题

我明白你碰到的问题了——你想筛选出列名中包含'tu'的列,按照字符串操作的思路尝试却报错'str' object has no attribute 'str',这其实是因为你用错了对象的方法。

错误原因

.str是Pandas里Series或Index对象专属的字符串操作访问器,单个字符串本身并没有这个属性。如果你直接对某个列名(单个字符串)调用.str,自然会触发这个错误。

正确的解决方案

我们需要对DataFrame的列名集合(也就是df.columns,它是一个Index对象)使用.str.contains()方法,生成布尔掩码后再筛选列。下面是完整的可运行代码:

import numpy as np
import pandas as pd
from sklearn.datasets import make_classification

# 生成分类数据集
X, y = make_classification(n_samples=1000, n_features=6, n_informative=3, n_classes=2, random_state=0, scale=10, shuffle=False)

# 创建DataFrame,这里特意设置了几个含'tu'的列名方便测试
df = pd.DataFrame(X, columns=['tutu_col', 'col_1', 'col_with_tu', 'col_2', 'tu_in_name', 'col_3'])

# 1. 生成布尔掩码:标记哪些列名包含'tu'
column_mask = df.columns.str.contains('tu')
# 2. 用掩码筛选出目标列
filtered_df = df.loc[:, column_mask]

# 查看筛选后的结果
print(filtered_df.head())

额外小技巧

如果需要不区分大小写筛选(比如匹配'Tu'、'TU'也能生效),可以给contains()加case=False参数:

column_mask = df.columns.str.contains('tu', case=False)

这样就能得到你想要的、仅包含列名含'tu'的DataFrame了~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:16:39