在本章中,我们将使用基本系列/索引来讨论字符串操作。在随后的章节中,将学习如何将这些字符串函数应用于数据帧(DataFrame)。

Pandas提供了一组字符串函数,可以方便地对字符串数据进行操作。 最重要的是,这些函数忽略(或排除)丢失/NaN值。

几乎这些方法都使用Python字符串函数(请参阅: http://docs.python.org/3/library/stdtypes.html#string-methods )。 因此,将Series对象转换为String对象,然后执行该操作。

下面来看看每个操作的执行和说明。

编号 函数 描述
1 lower() Series/Index中的字符串转换为小写。
2 upper() Series/Index中的字符串转换为大写。
3 len() 计算字符串长度。
4 strip() 帮助从两侧的系列/索引中的每个字符串中删除空格(包括换行符)。
5 split(' ') 用给定的模式拆分每个字符串。
6 cat(sep=' ') 使用给定的分隔符连接系列/索引元素。
7 get_dummies() 返回具有单热编码值的数据帧(DataFrame)。
8 contains(pattern) 如果元素中包含子字符串,则返回每个元素的布尔值True,否则为False
9 replace(a,b) 将值a替换为值b
10 repeat(value) 重复每个元素指定的次数。
11 count(pattern) 返回模式中每个元素的出现总数。
12 startswith(pattern) 如果系列/索引中的元素以模式开始,则返回true
13 endswith(pattern) 如果系列/索引中的元素以模式结束,则返回true
14 find(pattern) 返回模式第一次出现的位置。
15 findall(pattern) 返回模式的所有出现的列表。
16 swapcase 变换字母大小写。
17 islower() 检查系列/索引中每个字符串中的所有字符是否小写,返回布尔值
18 isupper() 检查系列/索引中每个字符串中的所有字符是否大写,返回布尔值
19 isnumeric() 检查系列/索引中每个字符串中的所有字符是否为数字,返回布尔值。

现在创建一个系列,看看上述所有函数是如何工作的。

  1. import pandas as pd
  2. import numpy as np
  3. s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu'])
  4. print (s)
Python

执行上面示例代码,得到以下结果 -

  1. 0 Tom
  2. 1 William Rick
  3. 2 John
  4. 3 Alber@t
  5. 4 NaN
  6. 5 1234
  7. 6 SteveMinsu
  8. dtype: object
Shell

1. lower()函数示例

  1. import pandas as pd
  2. import numpy as np
  3. s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu'])
  4. print (s.str.lower())
Python

执行上面示例代码,得到以下结果 -

  1. 0 tom
  2. 1 william rick
  3. 2 john
  4. 3 alber@t
  5. 4 NaN
  6. 5 1234
  7. 6 steveminsu
  8. dtype: object
Shell

2. upper()函数示例

  1. import pandas as pd
  2. import numpy as np
  3. s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu'])
  4. print (s.str.upper())
Python

执行上面示例代码,得到以下结果 -

  1. 0 TOM
  2. 1 WILLIAM RICK
  3. 2 JOHN
  4. 3 ALBER@T
  5. 4 NaN
  6. 5 1234
  7. 6 STEVESMITH
  8. dtype: object
Shell

3. len()函数示例

  1. import pandas as pd
  2. import numpy as np
  3. s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu'])
  4. print (s.str.len())
Python

执行上面示例代码,得到以下结果 -

  1. 0 3.0
  2. 1 12.0
  3. 2 4.0
  4. 3 7.0
  5. 4 NaN
  6. 5 4.0
  7. 6 10.0
  8. dtype: float64
Shell

4. strip()函数示例

  1. import pandas as pd
  2. import numpy as np
  3. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  4. print (s)
  5. print ("=========== After Stripping ================")
  6. print (s.str.strip())
Python

执行上面示例代码,得到以下结果 -

  1. 0 Tom
  2. 1 William Rick
  3. 2 John
  4. 3 Alber@t
  5. dtype: object
  6. =========== After Stripping ================
  7. 0 Tom
  8. 1 William Rick
  9. 2 John
  10. 3 Alber@t
  11. dtype: object
Shell

5. split(pattern)函数示例

  1. import pandas as pd
  2. import numpy as np
  3. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  4. print (s)
  5. print ("================= Split Pattern: ==================")
  6. print (s.str.split(' '))
Python

执行上面示例代码,得到以下结果 -

  1. 0 Tom
  2. 1 William Rick
  3. 2 John
  4. 3 Alber@t
  5. dtype: object
  6. ================= Split Pattern: ==================
  7. 0 [Tom, ]
  8. 1 [, William, Rick]
  9. 2 [John]
  10. 3 [Alber@t]
  11. dtype: object
Shell

6. cat(sep=pattern)函数示例

  1. import pandas as pd
  2. import numpy as np
  3. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  4. print (s.str.cat(sep=' <=> '))
Python

执行上面示例代码,得到以下结果 -

  1. Tom <=> William Rick <=> John <=> Alber@t
Shell

7. get_dummies()函数示例

  1. import pandas as pd
  2. import numpy as np
  3. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  4. print (s.str.get_dummies())
Python

执行上面示例代码,得到以下结果 -

  1. William Rick Alber@t John Tom
  2. 0 0 0 0 1
  3. 1 1 0 0 0
  4. 2 0 0 1 0
  5. 3 0 1 0 0
Shell

8. contains()函数示例

  1. import pandas as pd
  2. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  3. print (s.str.contains(' '))
Python

执行上面示例代码,得到以下结果 -

  1. 0 True
  2. 1 True
  3. 2 False
  4. 3 False
  5. dtype: bool
Shell

9. replace(a,b)函数示例

  1. import pandas as pd
  2. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  3. print (s)
  4. print ("After replacing @ with $: ============== ")
  5. print (s.str.replace('@','$'))
Python

执行上面示例代码,得到以下结果 -

  1. 0 Tom
  2. 1 William Rick
  3. 2 John
  4. 3 Alber@t
  5. dtype: object
  6. After replacing @ with $: ==============
  7. 0 Tom
  8. 1 William Rick
  9. 2 John
  10. 3 Alber$t
  11. dtype: object
Shell

10. repeat(value)函数示例

  1. import pandas as pd
  2. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  3. print (s.str.repeat(2))
Python

执行上面示例代码,得到以下结果 -

  1. 0 Tom Tom
  2. 1 William Rick William Rick
  3. 2 JohnJohn
  4. 3 Alber@tAlber@t
  5. dtype: object
Shell

11. count(pattern)函数示例

  1. import pandas as pd
  2. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  3. print ("The number of 'm's in each string:")
  4. print (s.str.count('m'))
Python

执行上面示例代码,得到以下结果 -

  1. The number of 'm's in each string:
  2. 0 1
  3. 1 1
  4. 2 0
  5. 3 0
  6. dtype: int64
Shell

12. startswith(pattern)函数示例

  1. import pandas as pd
  2. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  3. print ("Strings that start with 'T':")
  4. print (s.str. startswith ('T'))
Python

执行上面示例代码,得到以下结果 -

  1. Strings that start with 'T':
  2. 0 True
  3. 1 False
  4. 2 False
  5. 3 False
  6. dtype: bool
Shell

13. endswith(pattern)函数示例

  1. import pandas as pd
  2. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  3. print ("Strings that end with 't':")
  4. print (s.str.endswith('t'))
Python

执行上面示例代码,得到以下结果 -

  1. Strings that end with 't':
  2. 0 False
  3. 1 False
  4. 2 False
  5. 3 True
  6. dtype: bool
Shell

14. find(pattern)函数示例

  1. import pandas as pd
  2. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  3. print (s.str.find('e'))
Python

执行上面示例代码,得到以下结果 -

  1. 0 -1
  2. 1 -1
  3. 2 -1
  4. 3 3
  5. dtype: int64
Shell

注意:-1表示元素中没有这样的模式可用。

15. findall(pattern)函数示例

  1. import pandas as pd
  2. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  3. print (s.str.findall('e'))
Python

执行上面示例代码,得到以下结果 -

  1. 0 []
  2. 1 []
  3. 2 []
  4. 3 [e]
  5. dtype: object
Shell

空列表([])表示元素中没有这样的模式可用。

16. swapcase()函数示例

  1. import pandas as pd
  2. s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t'])
  3. print (s.str.swapcase())
Python

执行上面示例代码,得到以下结果 -

  1. 0 tOM
  2. 1 wILLIAM rICK
  3. 2 jOHN
  4. 3 aLBER@T
  5. dtype: object
Shell

17. islower()函数示例

  1. import pandas as pd
  2. s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t'])
  3. print (s.str.islower())
Python

执行上面示例代码,得到以下结果 -

  1. 0 False
  2. 1 False
  3. 2 False
  4. 3 False
  5. dtype: bool
Shell

18. isupper()函数示例

  1. import pandas as pd
  2. s = pd.Series(['TOM', 'William Rick', 'John', 'Alber@t'])
  3. print (s.str.isupper())
Python

执行上面示例代码,得到以下结果 -

  1. 0 True
  2. 1 False
  3. 2 False
  4. 3 False
  5. dtype: bool
Shell

19. isnumeric()函数示例

  1. import pandas as pd
  2. s = pd.Series(['Tom', '1199','William Rick', 'John', 'Alber@t'])
  3. print (s.str.isnumeric())
Python

执行上面示例代码,得到以下结果 -

  1. 0 False
  2. 1 True
  3. 2 False
  4. 3 False
  5. 4 False
  6. dtype: bool

Pandas字符串和文本数据的更多相关文章

  1. pandas处理大文本数据

    当数据文件是百万级数据时,设置chunksize来分批次处理数据 案例:美国总统竞选时的数据分析 读取数据 import numpy as np import pandas as pdfrom pan ...

  2. 机器学习入门-文本数据-构造词频词袋模型 1.re.sub(进行字符串的替换) 2.nltk.corpus.stopwords.words(获得停用词表) 3.nltk.WordPunctTokenizer(对字符串进行分词操作) 4.np.vectorize(对函数进行向量化) 5. CountVectorizer(构建词频的词袋模型)

    函数说明: 1. re.sub(r'[^a-zA-Z0-9\s]', repl='', sting=string)  用于进行字符串的替换,这里我们用来去除标点符号 参数说明:r'[^a-zA-Z0- ...

  3. 采用Json字符串,往服务器回传大量富文本数据时,需要注意的地方,最近开发时遇到的问题。

    json字符串中存在常规的用户输入的字符串,和很多的富文本样式标签(用户不能直接看到,点击富文本编辑器中的html源码按钮能看到),例如下面的: <p><strong>富文本& ...

  4. Python文本数据互相转换(pandas and win32com)

    (工作之后,就让自己的身心都去休息吧) 今天介绍一下文本数据的提取和转换,这里主要实例的转换为excel文件(.xlsx)转换world文件(.doc/docx),同时需要使用win32api,同py ...

  5. SQL server 存储过程 C#调用Windows CMD命令并返回输出结果 Mysql删除重复数据保留最小的id C# 取字符串中间文本 取字符串左边 取字符串右边 C# JSON格式数据高级用法

    create proc insertLog@Title nvarchar(50),@Contents nvarchar(max),@UserId int,@CreateTime datetimeasi ...

  6. 【转载】socket通信-C#实现tcp收发字符串文本数据

    在日常碰到的项目中,有些场景需要发送文本数据,也就是字符串,比如简单的聊天文字,JSON字符串等场景.那么如何如何使用SharpSocket来收发此类数据呢?其中要掌握的关键点是什么呢? 点击查看原博 ...

  7. JAVASE02-Unit08: 文本数据IO操作 、 异常处理

    Unit08: 文本数据IO操作 . 异常处理 * java.io.ObjectOutputStream * 对象输出流,作用是进行对象序列化 package day08; import java.i ...

  8. 《Python CookBook2》 第一章 文本 - 过滤字符串中不属于指定集合的字符 && 检查一个字符串是文本还是二进制

    过滤字符串中不属于指定集合的字符 任务: 给定一个需要保留的字符串的集合,构建一个过滤函数,并可将其应用于任何字符串s,函数返回一个s的拷贝,该拷贝只包含指定字符集合中的元素. 解决方案: impor ...

  9. MySQL中游标使用以及读取文本数据

    原文:MySQL中游标使用以及读取文本数据 前言 之前一直没有接触数据库的学习,只是本科时候修了一本数据库基本知识的课.当时只对C++感兴趣,天真的认为其它的课都没有用,数据库也是半懂不懂,胡乱就考试 ...

随机推荐

  1. delphi--自带控件(Tcheckbox、TComBobox、TpageControl、TDBGrid,TScrollBox,TEdit)

    一.TCheckBox 使CheckBox选中CheckBox1.Checked := True;选择发生变化 ,OnClick事件if CheckBox1.Checked thenbegin //. ...

  2. Java 语言基础(一)

    大多数编程语言都包括以下基本内容: 关键字 标识符 注释 常量和变量 运算符 语句 函数 数组 学习语言最重要的两点: 该语言基础的表现形式是什么 这些东西什么时候使用 关键字 在程序语言中有特殊含义 ...

  3. 详细介绍Redis的几种数据结构以及使用注意事项(转)

    原文:详细介绍Redis的几种数据结构以及使用注意事项 1. Overview 1.1 资料 <The Little Redis Book>,最好的入门小册子,可以先于一切文档之前看,免费 ...

  4. CNI Proposal 摘要

    原文连接:https://github.com/containernetworking/cni/blob/master/SPEC.md General consideration CNI的想法是先让容 ...

  5. 【我的Android进阶之旅】 Android Studio插件之Jenkins插件介绍

    一Jenkins插件功能介绍 1Jenkins任务列表 2切换Jenkins分组 3构建Jenkins任务 4进入构建Jenkins任务的页面 5进入最后一次构建Jenkins任务的页面 6增加Jen ...

  6. 我的Android进阶之旅------>解决Android Studio编译后安装apk报错:The APK file does not exist on disk

    1.错误描述 今天用Android Studio编译应用后安装APK的时候,报错了,错误如下所示: The APK file build\outputs\apk\OYP_2.3.4_I2Base_64 ...

  7. hibernate set的3个属性

    inverse 属性 在hibernate中通过对 inverse 属性的来决定是由双向关联的哪一方来维护表和表之间的关系. inverse = false 的为主动方.inverse = true ...

  8. android自定义控件(一)MeasureSpec 与 ListView.onMeasure

    A MeasureSpec encapsulates the layout requirements passed from parent to child. Each MeasureSpec rep ...

  9. mysql乱码修改character_set_server

    [mac] 1.使用任何一个客房端或者命令行查询一下编码,俺用的是MySQLWorkbench SHOW VARIABLES LIKE 'character_set_%'; 2.发现编码是charac ...

  10. RTSP客户端接收存储数据(live555库中的testRTSPClient实例)

    1.testRTSPClient简介 testRTSPClient是个简单的客户端实例,这个实例对rtsp数据交互作了详细的描述,其中涉及到rtsp会话的两个概念Source和Sink. Source ...