目录

使用文本数据(Working with Text Data)

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

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

几乎所有这些方法都适用于Python字符串函数(参见: https://docs.python.org/3/library/stdtypes.html#string-methods : https://docs.python.org/3/library/stdtypes.html#string-methods )。 因此,将Series Object转换为String Object,然后执行操作。

现在让我们看看每个操作的执行情况。

S.No 功能 描述
1lower() 将Series/Index中的字符串转换为小写。
2upper() 将Series/Index中的字符串转换为大写。
3len() 计算字符串长度()。
4strip() 帮助从两侧的系列/索引中的每个字符串中剥离空白(包括换行符)。
5 分裂(' ') 使用给定模式拆分每个字符串。
6 猫(sep ='') 使用给定的分隔符连接系列/索引元素。
7get_dummies() 返回具有One-Hot编码值的DataFrame。
8contains(pattern) 如果子元素包含在元素中,则返回每个元素的布尔值True,否则返回False。
9replace(a,b) 用值b替换值b
10repeat(value) 以指定的次数重复每个元素。
11count(pattern) 返回每个元素中pattern的外观计数。
12startswith(pattern) 如果Series/Index中的元素以模式开头,则返回true。
13endswith(pattern) 如果Series/Index中的元素以模式结束,则返回true。
14find(pattern) 返回第一次出现的模式的第一个位置。
15findall(pattern) 返回所有模式的列表。
16swapcase 将表壳置于下/上。
17islower() 检查Series/Index中每个字符串中的所有字符是否均为小写。 返回布尔值
18isupper() 检查Series/Index中每个字符串中的所有字符是否都是大写。 返回布尔值。
19isnumeric() 检查Series/Index中每个字符串中的所有字符是否都是数字。 返回布尔值。

现在让我们创建一个系列,看看上述所有功能是如何工作的。

import pandas as pd
import numpy as np
s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveSmith'])
print s

output如下 -

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

lower()

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

output如下 -

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

upper()

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

output如下 -

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

len()

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

output如下 -

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

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()

output如下 -

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

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(' ')

output如下 -

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

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='_')

output如下 -

Tom _ William Rick_John_Alber@t

get_dummies()

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

output如下 -

   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

contains ()

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

output如下 -

0   True
1   True
2   False
3   False
dtype: bool

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('@','$')

output如下 -

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

repeat(value)

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

output如下 -

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

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')

output如下 -

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

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')

output如下 -

0  True
1  False
2  False
3  False
dtype: bool

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')

output如下 -

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

find(pattern)

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

output如下 -

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

“-1”表示元素中没有这样的模式。

findall(pattern)

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

output如下 -

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

空列表([])表示元素中没有此类模式。

swapcase()

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

output如下 -

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

islower()

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

output如下 -

0  False
1  False
2  False
3  False
dtype: bool

isupper()

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

output如下 -

0  False
1  False
2  False
3  False
dtype: bool

isnumeric()

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

output如下 -

0  False
1  False
2  False
3  False
dtype: bool
↑回到顶部↑
WIKI教程 @2018