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

使用pandas按分隔符拆分数据行时遇DataFrame无str属性报错如何解决

错误原因

你在调用split(expand=True)后返回的是多列DataFrame对象,而.str是Pandas Series(单列)专属的字符串访问器,不能直接用在DataFrame上,因此触发属性不存在的报错。你尝试的to_string()会将整列数据合并为单个长字符串,完全不满足逐行拆分的需求,自然也会报错。

解决方案

你的文本格式规则固定,更适合用正则提取的方式一步获取所有需要的字段,逻辑更清晰也不会出现类型错误:

import pandas as pd

# 正则分组分别匹配城市、括号内区域、院校名三个字段
pattern = r'MAP (\w+), \((.*?)\) Location (\w+)'

# 直接对原列提取结构化内容
df_result = df["columnnname"].str.extract(pattern, expand=True)

# 重命名列并格式化院校名字段
df_result.columns = ["Place", "所属区域", "Location"]
df_result["Location"] = df_result["Location"].str.replace("_", " ").str.title()

处理完成的df_result就是你需要的结构化结果,可以直接查看或导出使用。

如果坚持使用多次split的拆分方式,需要每次拆分后取对应单列保持为Series类型再继续字符串操作,示例如下:

# 提取城市字段
place_col = df["columnnname"].str.split(",", expand=True)[0].str.replace("MAP ", "").str.strip()
# 拆分剩余部分获取区域和院校字段
rest_part = df["columnnname"].str.split(",", expand=True)[1]
region_col = rest_part.str.split("Location", expand=True)[0].str.strip()
location_col = rest_part.str.split("Location", expand=True)[1].str.split(" is having", expand=True)[0].str.replace("_", " ").str.strip().str.title()
# 合并为结果表
df_result = pd.concat([place_col, region_col, location_col], axis=1)
df_result.columns = ["Place", "所属区域", "Location"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:36:01