Pandas最常用的7种字符串处理方法

Pandas是一个强大的数据处理工具,除了能处理数值和时间序列等数据类型外,还能够方便地处理字符串数据。

常用的字符串处理函数如下表所示:

函数名称 函数功能说明
lower() 将的字符串转换为小写。
upper() 将的字符串转换为大写。
len() 得出字符串的长度。
strip() 去除字符串两边的空格(包含换行符)。
split() 用指定的分割符分割字符串。
cat(sep="") 用给定的分隔符连接字符串元素。
get_dummies() 返回一个带有独热编码值的 DataFrame 结构。
contains(pattern) 如果子字符串包含在元素中,则为每个元素返回一个布尔值 True,否则为 False。
replace(a,b) 将值 a 替换为值 b。
count(pattern) 返回每个字符串元素出现的次数。
startswith(pattern) 如果 Series 中的元素以指定的字符串开头,则返回 True。
endswith(pattern) 如果 Series 中的元素以指定的字符串结尾,则返回 True。
findall(pattern) 以列表的形式返出现的字符串。
swapcase() 交换大小写。
islower() 返回布尔值,检查 Series 中组成每个字符串的所有字符是否都为小写。
issupper() 返回布尔值,检查 Series 中组成每个字符串的所有字符是否都为大写。
isnumeric() 返回布尔值,检查 Series 中组成每个字符串的所有字符是否都为数字。
repeat(value) 以指定的次数重复每个元素。
find(pattern) 返回字符串第一次出现的索引位置。

下面就来详细介绍一下Pandas处理字符串的最常用的8种方法。

str.lower()和str.upper()方法

str.lower()方法可以将字符串全部转换成小写字母。
str.upper()方法可以将字符串全部转换成
大写字母。

示例如下:

import pandas as pd

df = pd.DataFrame({'string': ['Lower', 'UPPER', 'Mixed', 'lowercase and UPPERCASE']})

# 转换成小写
df['lower'] = df['string'].str.lower()

# 转换成大写
df['upper'] = df['string'].str.upper()

print(df)

输出:

                    string                    lower                    upper
0                    Lower                     lower                     LOWER
1                    UPPER                     upper                     UPPER
2                    Mixed                     mixed                     MIXED
3  lowercase and UPPERCASE  lowercase and uppercase  LOWERCASE AND UPPERCASE

str.strip()方法

str.strip()方法可以去掉字符串开头和结尾的空格。

比如:

import pandas as pd

df = pd.DataFrame({'string': ['  Leading spaces', 'Trailing spaces   ', '  Both sides  ', 'No spaces']})

# 去掉空格
df['stripped'] = df['string'].str.strip()

print(df)

输出结果为:

               string           stripped
0     Leading spaces    Leading spaces
1   Trailing spaces   Trailing spaces
2        Both sides          Both sides
3          No spaces          No spaces

str.replace()方法

str.replace()方法可以将字符串中的某个子串替换为另一个子串。

示例:

import pandas as pd

df = pd.DataFrame({'string': ['hello, world', 'goodbye, world', 'hello, pandas']})

# 替换子串
df['replaced'] = df['string'].str.replace('world', 'pandas')

print(df)

输出:

           string         replaced
0    hello, world   hello, pandas
1  goodbye, world  goodbye, pandas
2   hello, pandas   hello, pandas

str.split()方法

str.split()方法可以将字符串按照某个分隔符分割成若干个子串,并返回一个包含这些子串的列表。

例如:

import pandas as pd

df = pd.DataFrame({'string': ['apple,banana,orange', 'dog,cat,rabbit', 'John,Paul,George,Ringo']})

# 按逗号分割
df['split'] = df['string'].str.split(',')

print(df)

输出:

                  string                           split
0     apple,banana,orange        [apple, banana, orange]
1           dog,cat,rabbit              [dog, cat, rabbit]
2  John,Paul,George,Ringo  [John, Paul, George, Ringo]

str.extract()方法

str.extract()方法可以从字符串中提取出满足某个正则表达式的子串。

示例:

import pandas as pd

s_extract = pd.Series(['apple_123', 'banana_456', 'carrot_789', 'dog'])
s_extract = s_extract.str.extract(r'(\w+)_(\d+)')
print(s_extract)

输出结果为:

        0    1
0   apple  123
1  banana  456
2  carrot  789
3     NaN  NaN

str.contains()

str.contains()方法用于检查字符串是否包含指定子串,返回布尔值。

例如:

import pandas as pd

# 创建示例Series
s = pd.Series(['apple', 'banana', 'carrot', 'dog'])
s_contains = s.str.contains('a')
print(s_contains)

输出结果为:

0     True
1     True
2     True
3    False
dtype: bool

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Pandas最常用的7种字符串处理方法 - Python技术站

(2)
上一篇 2023年3月5日
下一篇 2023年3月5日

相关文章

  • Pandas 读写excel

    下面是Pandas读写Excel的完整攻略: 需要的Python包 在使用Pandas读写Excel之前,需要确保已经安装以下两个Python包: pandas openpyxl 可以使用以下命令来安装这两个包: pip install pandas openpyxl 读取Excel文件 使用Pandas读取Excel文件可以轻松地将Excel文件转换为Pa…

    python-answer 2023年3月27日
    00
  • 如何在Pandas DataFrame中把浮点数转换为数据时间

    在Pandas中,将浮点数转换为日期时间有两种常见的方式:使用to_datetime()函数或使用astype()函数。下面分别详细介绍这两种方法。 使用to_datetime()函数 使用to_datetime()函数可以将浮点数转换为日期时间。to_datetime()函数需要传入一个Series或DataFrame对象,以及日期时间格式的字符串。具体步…

    python-answer 2023年3月27日
    00
  • Python中的Pandas 时间函数 time 、datetime 模块和时间处理基础讲解

    Python中的Pandas时间函数time、datetime模块和时间处理基础讲解 时间函数time 在Python中,time是一个可以进行时间计算,处理和表示的模块。这个模块内包含了许多处理时间的函数,例如获取当前时间,计算时间差,格式化时间字符串等等。下面我们将对一些基础的时间函数进行介绍: 获取当前时间 获取当前时间可以使用time模块中的time…

    python 2023年5月14日
    00
  • pandas分组聚合详解

    Pandas 分组聚合详解 简介 在数据处理中,很常见的一种需求是把数据按照某些标准进行分组,然后在每个组内进行聚合操作。比如求每个人的年龄平均值,在每个城市中计算房价的均值等等。这个时候Pandas的分组聚合就可以帮我们轻松实现。 分组操作 Pandas中的分组操作主要是通过groupby()函数来实现的。下面我们用一个示例数据集进行分析: import …

    python 2023年5月14日
    00
  • Pandas和PostgreSQL之间的区别

    Pandas是一款Python数据分析库,主要用于数据解析、数据清洗、数据统计和建模等。它提供了高效的数据操作与分析接口,支持众多的数据输入输出格式,例如CSV、Excel、SQL等。Pandas提供了Series和DataFrame两种数据结构,它们是数据操作与统计的基础。 PostgreSQL是一款高性能的开源关系型数据库管理系统,它与传统的关系型数据库…

    python-answer 2023年3月27日
    00
  • Python3 pandas 操作列表实例详解

    Python3 pandas操作列表实例详解 什么是pandas Pandas是一个开源的数据分析和操作工具,它是构建在NumPy之上的,旨在提供一种有效的方式来处理大型数据集,让你可以进行快速的数据操作、清洗和转换。Pandas具有强大的数据处理、整合和分组功能,使它成为数据分析的理想选择。 pandas拥有两种主要数据结构,分别是Series和DataF…

    python 2023年5月14日
    00
  • 如何扁平化Pandas DataFrame列中的分层索引

    Pandas DataFrame中的分层索引可以使得数据结构更加灵活,但有时候需要将列的分层索引“扁平化”,这样可以方便数据的处理和展示。本文将提供详细的步骤和实例说明。 什么是分层索引? 在Pandas DataFrame中,可以通过多维数组或元组嵌套的方式创建“分层索引”,也称为“层次化索引”。例如,在以下的DataFrame中,使用两个嵌套的列表创建了…

    python-answer 2023年3月27日
    00
  • 如何在Pandas数据框架中添加标题行

    要在pandas数据框架中添加标题行(也被称为列名),可以按照以下步骤操作: 1.首先创建一个数据框架。可以使用以下代码创建一个数据框架: import pandas as pd df = pd.DataFrame({‘col1’:[1, 2, 3], ‘col2’:[4, 5, 6], ‘col3’:[7, 8, 9]}) print(df) 输出: co…

    python-answer 2023年3月27日
    00
合作推广
合作推广
分享本页
返回顶部