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

相关推荐
静听山水7 分钟前
mysql语句执行过程
数据库·mysql
虽千万人 吾往矣25 分钟前
golang gorm
开发语言·数据库·后端·tcp/ip·golang
mariokkm1 小时前
Django一分钟:在Django中怎么存储树形结构的数据,DRF校验递归嵌套模型的替代方案
数据库·django·sqlite
Wang's Blog2 小时前
Redis: 集群环境搭建,集群状态检查,分析主从日志,查看集群信息
数据库·redis
容器( ु⁎ᴗ_ᴗ⁎)ु.。oO2 小时前
MySQL事务
数据库·mysql
安静的_显眼包O_o3 小时前
【数据分析】DataFrame.query()
数据挖掘·数据分析·pandas
cyt涛4 小时前
MyBatis 学习总结
数据库·sql·学习·mysql·mybatis·jdbc·lombok
Rookie也要加油4 小时前
01_SQLite
数据库·sqlite
liuxin334455664 小时前
教育技术革新:SpringBoot在线教育系统开发
数据库·spring boot·后端
少女的迷鹿5 小时前
Paper:NSG(Navigating Spreading-out Graph)
数据库