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

yizhihongxing

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搭配lambda组合使用详解

    Pandas搭配lambda组合使用详解 在Pandas中,我们可以使用lambda表达式对DataFrame进行高效的处理和变换。本文将介绍如何将Pandas和lambda表达式组合使用,以实现对数据的快速处理。 lambda表达式简介 lambda是Python中的一个关键字,用于定义匿名函数,也就是没有函数名的函数。语法如下: lambda argum…

    python 2023年5月14日
    00
  • 如何在Pandas中扁平化MultiIndex

    在Pandas中,MultiIndex可以在数据分析和数据聚合中非常便利,它能够用于解决很多复杂的问题。但是,在一些特别的情况下,MultiIndex也可能给分析带来一些困扰,尤其是当需要将复合索引转化成标准的索引时,可能会带来一定的复杂性。在这种情况下,我们需要将MultiIndex“扁平化”,本文将详细介绍如何在Pandas中实现这一操作。 步骤一:导入…

    python-answer 2023年3月27日
    00
  • Python Pandas中合并数据的5个函数使用详解

    下面我将详细讲解“Python Pandas中合并数据的5个函数使用详解”的完整攻略。 简介 在数据处理中,我们常常需要将不同来源的数据合并在一起,以方便分析和处理。在Python Pandas中,有很多种方法可以达到这个目的,其中比较常用的有以下5个函数: pd.concat() : 在行或列上拼接两个或多个DataFrame或Series df.appe…

    python 2023年5月14日
    00
  • 两个Pandas系列的加、减、乘、除法

    接下来我将详细讲解Pandas中两个系列的加、减、乘、除法的攻略,并结合实例进行说明。 Series的算术运算 Series对象可以通过加减乘除等操作进行算术运算。这些运算默认对齐索引,并返回一个新的Series对象。 下面是一些Series对象的算术运算的实例: import pandas as pd s1 = pd.Series([1, 2, 3], i…

    python-answer 2023年3月27日
    00
  • Python运用于数据分析的简单教程

    Python运用于数据分析的简单教程 数据分析是如今越来越重要的一个领域,同时Python也成为数据分析的热门工具之一。在本教程中,我们将向您介绍如何使用Python进行数据分析的基础知识和操作过程。 安装Python和必要的包 首先,您需要安装Python以及与数据分析相关的各种包。以下是基本的安装步骤: 下载并安装 Python 安装 NumPy pip…

    python 2023年5月14日
    00
  • 如何在Python中使用Pandas从excel表中创建一个带有多个索引的数据透视表

    通过Pandas,我们可以很方便地从Excel表中读取数据并创建数据透视表。一个数据透视表可以是带有一个或多个索引的,也可以是带有多个计算值的表格,便于对大数据进行分析和可视化。下面是在Python中使用Pandas创建一个带有多个索引的数据透视表的步骤。 步骤一:导入Pandas库 首先要导入pandas库,具体代码如下: import pandas as…

    python-answer 2023年3月27日
    00
  • Series和DataFrame使用简单入门

    Series和DataFrame是Pandas库中两个最为基础和最为重要的数据结构,对于Pandas的使用者来说,掌握它们的使用方法相当重要。本文将从如何创建Series和DataFrame、如何对它们进行操作等方面,为大家提供一份基础入门攻略。 1. Series 1.1 创建Series 在Pandas中,可以通过列表、数组、字典等方式创建Series。…

    python 2023年6月13日
    00
  • Python数据处理的26个Pandas实用技巧总结

    下面是“Python数据处理的26个Pandas实用技巧总结”的完整攻略。 1. 简介 Pandas是使用Python进行数据处理和数据分析的一种工具,提供了分析、清洗、转换和操作数据的函数和方法。本攻略总结了Pandas中的26个实用技巧,帮助你更高效地处理数据。 2. 基本操作 2.1 导入Pandas库 在使用Pandas之前,需要导入Pandas库。…

    python 2023年5月14日
    00
合作推广
合作推广
分享本页
返回顶部