pandas字符串操作:大小写转换、连接、分割、包含等

大小写转换

python 复制代码
import pandas as pd

data = {
  'text': ['Hello World', 'Python is Great', 'Data Science']
}
df = pd.DataFrame(data)
df.dropna(thresh=True)
c = df["text"].str.capitalize()
# 0        Hello world
# 1    Python is great
# 2       Data science
# Name: text, dtype: object

c = df["text"].str.upper()
# 0        HELLO WORLD
# 1    PYTHON IS GREAT
# 2       DATA SCIENCE

c = df["text"].str.title()
# 0        Hello World
# 1    Python Is Great
# 2       Data Science

c = df["text"].str.lower()
# 0        hello world
# 1    python is great
# 2       data science

c = df["text"].str.swapcase()
# 0        hELLO wORLD
# 1    pYTHON IS gREAT
# 2       dATA sCIENCE

c = df["text"].str.casefold()
# 0        hello world
# 1    python is great
# 2       data science

字符串连接和分割

python 复制代码
c = df["text"].str.cat(sep=";")
# Hello World;Python is Great;Data Science

按照分号连接。

python 复制代码
sp = df["text"].str.split()
# 0         [Hello, World]
# 1    [Python, is, Great]
# 2        [Data, Science]

分割字符串

包含、以某字符串结尾

python 复制代码
c = df["text"].str.contains('is')
# 0    False
# 1     True
# 2    False

支持正则表达式。

python 复制代码
c = df["text"].str.endswith("e")
# 0    False
# 1    False
# 2     True
c = df["text"].str.startswith("D")

正则提取

python 复制代码
import pandas as pd

data = {
    'text': ['Hello World', 'Python is Great', 'Data Science']
}
df = pd.DataFrame(data)
c = df["text"].str.extract("(\w+) (\w+)")
print(c)
# 0   Hello    World
# 1  Python       is
# 2    Data  Science

参考

https://pandas.pydata.org/docs/reference/api/pandas.Series.str.cat.html

相关推荐
jason_renyu12 小时前
数据库关联查询(JOIN)完全指南
数据库·数据库关联查询·关联查询指南·数据库关联查询学习
是码龙不是码农12 小时前
MySQL 锁的完整分类与详解
数据库·mysql·
..过云雨12 小时前
【MySQL】3. MySQL库的操作
数据库·mysql
wregjru12 小时前
【操作系统】12.Linux 多线程同步与互斥详解
数据库·mysql
小李独爱秋12 小时前
模拟面试:简述一下MySQL数据库的备份方式。
数据库·mysql·面试·职场和发展·数据备份
難釋懷13 小时前
Redis消息队列-基于Stream的消息队列-消费者组
数据库·redis·缓存
四七伵13 小时前
数据库必修课:MySQL金额字段用decimal还是bigint?
数据库·后端
diaya14 小时前
麒麟V10 x86系统安装mysql
数据库·mysql
LaughingZhu14 小时前
Product Hunt 每日热榜 | 2026-02-24
大数据·数据库·人工智能·经验分享·搜索引擎
QEasyCloud202215 小时前
WooCommerce 独立站系统集成技术方案
java·前端·数据库