Pandas字符串和文本数据,在本章中,我们将使用基本系列,索引来讨论字符串操作。在随后的章节中,将学习如何将这些字符串函数应用于数据帧(DataFrame)。
Pandas提供了一组字符串函数,可以方便地对字符串数据进行操作。 最重要的是,这些函数忽略了NaN
值。几乎这些方法都使用Python 字符串函数。因此,将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. lower()函数示例
执行上面示例代码,得到以下结果 –
2. upper()函数示例
执行上面示例代码,得到以下结果 –
3. len()函数示例
执行上面示例代码,得到以下结果 –
4. strip()函数示例
执行上面示例代码,得到以下结果 –
5. split(pattern)函数示例
执行上面示例代码,得到以下结果 –
6. cat(sep=pattern)函数示例
执行上面示例代码,得到以下结果 –
7. get_dummies()函数示例
执行上面示例代码,得到以下结果 –
8. contains()函数示例
执行上面示例代码,得到以下结果 –
9. replace(a,b)函数示例
执行上面示例代码,得到以下结果 –
10. repeat(value)函数示例
执行上面示例代码,得到以下结果 –
11. count(pattern)函数示例
执行上面示例代码,得到以下结果 –
12. startswith(pattern)函数示例
执行上面示例代码,得到以下结果 –
13. endswith(pattern)函数示例
执行上面示例代码,得到以下结果 –
14. find(pattern)函数示例
执行上面示例代码,得到以下结果 –
注意:
-1
表示元素中没有这样的模式可用。
15. findall(pattern)函数示例
执行上面示例代码,得到以下结果 –
空列表(
[]
)表示元素中没有这样的模式可用。
16. swapcase()函数示例
执行上面示例代码,得到以下结果 –
17. islower()函数示例
执行上面示例代码,得到以下结果 –
18. isupper()函数示例
执行上面示例代码,得到以下结果 –
19. isnumeric()函数示例
执行上面示例代码,得到以下结果 –