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

相关推荐
送秋三十五39 分钟前
MySQL DBA需要掌握的 7 个问题
数据库·mysql·dba
睡觉的时候不会困42 分钟前
MySQL 高可用方案之 MHA 架构搭建与实践
数据库·mysql·架构
kyle~42 分钟前
Qt---对话框QDialog
数据库·qt·microsoft
GBASE1 小时前
“G”术时刻:南大通用GBase 8c数据库权限管理场景实践(三)
数据库
GottdesKrieges2 小时前
OceanBase系统日志管理
数据库·oracle·oceanbase
小嵌同学3 小时前
Linux:malloc背后的实现细节
大数据·linux·数据库
R瑾安3 小时前
mysql安装(压缩包方式8.0及以上)
数据库·mysql
代码的余温3 小时前
MySQL Cluster核心优缺点
数据库·mysql
Mr.Entropy5 小时前
请求超过Spring线程池的最大线程(处理逻辑)
数据库·sql·spring
GBASE5 小时前
“G”术时刻:南大通用GBase 8c数据库权限管理场景实践(二)
数据库