Pandas字符串和文本数据

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

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

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

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

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

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

import pandas as pd
import numpy as np

s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu'])

print (s)

Python

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

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

Shell

1. lower()函数示例

import pandas as pd
import numpy as np

s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu'])

print (s.str.lower())

Python

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

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

Shell

2. upper()函数示例

import pandas as pd
import numpy as np

s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu'])

print (s.str.upper())

Python

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

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

Shell

3. len()函数示例

import pandas as pd
import numpy as np

s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu'])
print (s.str.len())

Python

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

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

Shell

4. strip()函数示例

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

Python

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

0             Tom 
1     William Rick
2             John
3          Alber@t
dtype: object
=========== After Stripping ================
0             Tom
1    William Rick
2            John
3         Alber@t
dtype: object

Shell

5. split(pattern)函数示例

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

Python

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

0             Tom 
1     William Rick
2             John
3          Alber@t
dtype: object
================= Split Pattern: ==================
0              [Tom, ]
1    [, William, Rick]
2               [John]
3            [Alber@t]
dtype: object

Shell

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

import pandas as pd
import numpy as np

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])

print (s.str.cat(sep=' <=> '))

Python

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

Tom  <=>  William Rick <=> John <=> Alber@t

Shell

7. get_dummies()函数示例

import pandas as pd
import numpy as np

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])

print (s.str.get_dummies())

Python

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

    William Rick  Alber@t  John  Tom 
0              0        0     0     1
1              1        0     0     0
2              0        0     1     0
3              0        1     0     0

Shell

8. contains()函数示例

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

Python

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

0     True
1     True
2    False
3    False
dtype: bool

Shell

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

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

Python

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

0             Tom 
1     William Rick
2             John
3          Alber@t
dtype: object
After replacing @ with $: ============== 
0             Tom 
1     William Rick
2             John
3          Alber$t
dtype: object

Shell

10. repeat(value)函数示例

import pandas as pd

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])

print (s.str.repeat(2))

Python

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

0                      Tom Tom 
1     William Rick William Rick
2                      JohnJohn
3                Alber@tAlber@t
dtype: object

Shell

11. count(pattern)函数示例

import pandas as pd

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])

print ("The number of 'm's in each string:")
print (s.str.count('m'))

Python

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

The number of 'm's in each string:
0    1
1    1
2    0
3    0
dtype: int64

Shell

12. startswith(pattern)函数示例

import pandas as pd

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])

print ("Strings that start with 'T':")
print (s.str. startswith ('T'))

Python

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

Strings that start with 'T':
0     True
1    False
2    False
3    False
dtype: bool

Shell

13. endswith(pattern)函数示例

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

Python

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

Strings that end with 't':
0    False
1    False
2    False
3     True
dtype: bool

Shell

14. find(pattern)函数示例

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

Python

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

0   -1
1   -1
2   -1
3    3
dtype: int64

Shell

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

15. findall(pattern)函数示例

import pandas as pd

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
print (s.str.findall('e'))

Python

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

0     []
1     []
2     []
3    [e]
dtype: object

Shell

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

16. swapcase()函数示例

import pandas as pd

s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t'])
print (s.str.swapcase())

Python

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

0             tOM
1    wILLIAM rICK
2            jOHN
3         aLBER@T
dtype: object

Shell

17. islower()函数示例

import pandas as pd

s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t'])
print (s.str.islower())

Python

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

0    False
1    False
2    False
3    False
dtype: bool

Shell

18. isupper()函数示例

import pandas as pd

s = pd.Series(['TOM', 'William Rick', 'John', 'Alber@t'])

print (s.str.isupper())

Python

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

0    True
1    False
2    False
3    False
dtype: bool

Shell

19. isnumeric()函数示例

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

Python

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

0    False
1     True
2    False
3    False
4    False
dtype: bool


 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小金子的夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值