【Python】 原生str 与 Pandas Series.str 系统总结
·
总结了原生
str和pd.Series.str用法规律,速查表可直接见第六节
规律放最前:
- Python 单个 str → split / index / replace / upper / lower
- Series → .str 批量操作
- 取拆分后的段 → .str.split(“_”).str[i]
- 匹配 / 过滤 → .str.contains / .str.startswith / .str.endswith
- 类型原则 :
- Series/Index 可直接用
.str, - list/tuple/array 需
pd.Series(); - 非字符串先转
str(); - 单个字符串用原生 .str
- Series/Index 可直接用
一、模拟数据
import pandas as pd
# 模拟学生 ID + 科目
students = [
"S01_Math_Alice",
"S02_English_Bob",
"S03_Math_Carol",
"S04_English_Dave",
"S05_Science_Eve",
"S06_Math_Frank",
"S07_Science_Grace",
]
# 转为 Series
student_series = pd.Series(students)
student_series
输出:
0 S01_Math_Alice
1 S02_English_Bob
2 S03_Math_Carol
3 S04_English_Dave
4 S05_Science_Eve
5 S06_Math_Frank
6 S07_Science_Grace
dtype: object
可以理解为每个元素是一个 “学生ID_科目_名字” 的字符串。
二、Python 原生 str 方法(单个字符串)
1. 拆分 / 拼接
s = "S01_Math_Alice"
s.split("_") # ['S01','Math','Alice']
"_".join(s.split("_")) # 'S01_Math_Alice'
2. 大小写
s.upper() # 'S01_MATH_ALICE'
s.lower() # 's01_math_alice'
s.capitalize() # 'S01_math_alice'
3. 查找 / 判断
s.startswith("S01") # True
s.endswith("Alice") # True
"Math" in s # True
s.find("Math") # 3 (索引)
4. 替换 / 去空格
s.replace("Math","English") # 'S01_English_Alice'
s.strip() # 去掉首尾空格
split 分开,join 合并;upper 大写,lower 小写;start 开头,end 结尾,in 包含;replace 换掉,strip 去掉空白。
三、Pandas Series + str(批量操作)
1. 基本用法
# 拆分每个元素
student_series.str.split("_")
输出每个元素拆成 list:
0 ['S01','Math','Alice']
1 ['S02','English','Bob']
...
2. 取拆分后的段(.str[i])
# 学生 ID
student_series.str.split("_").str[0]
# 科目
student_series.str.split("_").str[1]
# 名字
student_series.str.split("_").str[2]
split分开,str[i]取段,Series + .str批量操作。
3. 字符串匹配 / 过滤
# 只选 Math 科目的学生
student_series[student_series.str.contains("Math")]
# 只选 S01 开头的学生
student_series[student_series.str.startswith("S01")]
# 只选名字以 'Alice' 结尾
student_series[student_series.str.endswith("Alice")]
4. 替换 / 大小写(批量)
# Math -> Science
student_series.str.replace("Math","Science")
# 大写
student_series.str.upper()
四、正则提取
# 提取学生 ID
student_series.str.extract(r"(S\d+)")
五、类型衔接:什么时候需要 pd.Series 转换
1. 可以直接用 .str
| 类型 | 是否可用 .str |
示例 |
|---|---|---|
| Series(元素是字符串或 object) | ✅ | student_series.str.split("_") |
| Index(列名或行索引) | ✅ | df.columns.str.replace("old","new") |
2. 需要先转换为 Series
| 类型 | 转换方法 | 示例 |
|---|---|---|
| list / tuple | pd.Series(list) |
pd.Series(["S01_Math","S02_Eng"]).str.split("_") |
| numpy array | pd.Series(arr) 或 pd.Series(arr).astype(str) |
pd.Series(np.array([1,2,3])).astype(str).str.zfill(2) |
| categorical | s.astype(str) |
s.astype(str).str.split("_") |
3. 不可用 .str 的类型
- 单个字符串 → 用原生
str方法 - 非字符串数组 → 需转换为字符串
Series / Index 可 str,list / tuple / array 先 pd.Series;非字符串先转 str;单个字符串用原生 str。
六、对比速查表
| 功能 | Python 原生 str | Series.str | 说明 / 输出类型 |
|---|---|---|---|
| 拆分 | s.split("_") |
s.str.split("_") |
返回 list |
| 取段 | lst[i] |
s.str.split("_").str[i] |
获取拆分后的第 i 段 |
| 查找 | "Math" in s |
s.str.contains("Math") |
返回布尔 Series |
| 开头/结尾 | s.startswith("S01") |
s.str.startswith("S01") / .str.endswith() |
返回布尔 Series |
| 替换 | s.replace("Math","Science") |
s.str.replace("Math","Science") |
批量替换 |
| 大小写 | s.upper() / s.lower() / s.capitalize() |
s.str.upper() / s.str.lower() / s.str.capitalize() |
批量转换 |
| 正则提取 | re.search(r"(S\d+)", s) |
s.str.extract(r"(S\d+)") |
批量抽取,返回 DataFrame |
| 去首尾空格 | s.strip() / s.lstrip() / s.rstrip() |
s.str.strip() / .str.lstrip() / .str.rstrip() |
去掉首尾/左/右空格 |
| 填充 / 补齐 | s.zfill(2) / s.rjust(5,"0") |
s.str.zfill(2) / s.str.rjust(5,"0") |
数字或字符填充,长度补齐 |
| 查找索引 | s.find("Math") / s.index("Math") |
s.str.find("Math") |
返回索引,找不到返回 -1(find)或报错(index) |
| 是否数字 | s.isdigit() |
s.str.isdigit() |
判断字符串是否为纯数字 |
| 是否字母 | s.isalpha() |
s.str.isalpha() |
判断是否全为字母 |
| 拼接 / 连接 | "_".join(list) |
s.str.cat(sep="_") |
将 list 或 Series 拼接成字符串 |
| 重复 | s*3 |
s.str.repeat(3) |
重复字符串 |
| 替换正则 | re.sub(r"\d+", "XX", s) |
s.str.replace(r"\d+", "XX", regex=True) |
正则批量替换 |
| 分隔指定字符前/后 | s.partition("_") |
s.str.partition("_") |
返回三段 tuple(左,分隔符,右) |
| 分隔指定字符前/后右 | s.rpartition("_") |
s.str.rpartition("_") |
从右侧分隔 |
| 匹配正则 | re.match(r"S\d+", s) |
s.str.match(r"S\d+") |
匹配开头是否符合正则,返回布尔 Series |
| 查找重复 / 唯一 | set([s1,s2,...]) |
s.str.unique() |
去重元素 / 返回唯一值 |
七、示例
# 选 Math 科目的学生
math_students = student_series[student_series.str.contains("Math")]
# 获取所有科目
subjects = student_series.str.split("_").str[1].unique()
# 获取 S01 学生的名字
student_series[student_series.str.startswith("S01")].str.split("_").str[2]
八、总结
- Python 单个 str → split / index / replace / upper / lower
- Series → .str 批量操作
- 取拆分后的段 → .str.split(“_”).str[i]
- 匹配 / 过滤 → .str.contains / .str.startswith / .str.endswith
- 类型原则 → Series/Index 可直接用 .str,list/tuple/array 需 pd.Series;非字符串先转 str;单个字符串用原生 str
更多推荐


所有评论(0)