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

相关推荐
正儿八经的少年2 小时前
布隆过滤器(解决redis缓存穿透步骤之一)
数据库·redis·缓存
xrandzj2 小时前
MySQL8.0 从零通关核心操作手册(Ubuntu实战版)
数据库·mysql
我不会插花弄玉2 小时前
4.数据类型【由浅入深-MySQL】
数据库·mysql
denggun123452 小时前
yield
前端·数据库·python
ltl3 小时前
SQLite Rollback Journal:写前拷贝与提交点
数据库
ltl3 小时前
TiFlash Learner:Raft 日志如何进列存
数据库
ltl3 小时前
BM25 与 Lucene Similarity:公式如何落到 postings
数据库
ltl3 小时前
RocksDB Block Cache 与 Bloom Filter:读放大怎么裁
数据库
deli0070074 小时前
JSON 树形查看器:粘贴即解析,折叠展开一目了然
前端·数据库·json·ai编程
国科安芯4 小时前
轨道供电韧性:ASP4644四通道降压架构在低轨卫星平台电源管理中的适用性分析
运维·网络·数据库·嵌入式硬件·架构·状态模式·低轨卫星星座