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

相关推荐
数据知道1 小时前
PostgreSQL 故障排查:万字详解如何找出数据库中的死锁
数据库·postgresql
AI_56782 小时前
阿里云OSS成本优化:生命周期规则+分层存储省70%
运维·数据库·人工智能·ai
choke2332 小时前
软件测试任务测试
服务器·数据库·sqlserver
龙山云仓2 小时前
MES系统超融合架构
大数据·数据库·人工智能·sql·机器学习·架构·全文检索
IT邦德2 小时前
OEL9.7 安装 Oracle 26ai RAC
数据库·oracle
jianghua0012 小时前
Django视图与URLs路由详解
数据库·django·sqlite
那我掉的头发算什么2 小时前
【Mybatis】Mybatis-plus使用介绍
服务器·数据库·后端·spring·mybatis
倔强的石头1062 小时前
关系数据库替换用金仓:数据迁移过程中的完整性与一致性风险
数据库·kingbase
_Johnny_2 小时前
ETCD 配额/空间告警模拟脚本
数据库·chrome·etcd
静听山水2 小时前
StarRocks查询加速
数据库