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

相关推荐
2301_8135995524 分钟前
Go语言怎么做秒杀系统_Go语言秒杀系统实战教程【实用】
jvm·数据库·python
NCIN EXPE5 小时前
redis 使用
数据库·redis·缓存
MongoDB 数据平台5 小时前
为编码代理引入 MongoDB 代理技能和插件
数据库·mongodb
极客on之路5 小时前
mysql explain type 各个字段解释
数据库·mysql
代码雕刻家5 小时前
MySQL与SQL Server的基本指令
数据库·mysql·sqlserver
lThE ANDE5 小时前
开启mysql的binlog日志
数据库·mysql
yejqvow125 小时前
CSS如何控制placeholder文字的颜色_使用--placeholder伪元素
jvm·数据库·python
oLLI PILO5 小时前
nacos2.3.0 接入pgsql或其他数据库
数据库
m0_743623925 小时前
HTML怎么创建多语言切换器_HTML语言选择下拉结构【指南】
jvm·数据库·python