Python Pandas Series.str.encode()
Series.str可以用来将系列的值作为字符串访问,并对其应用几种方法。Pandas Series.str.encode()函数用于在系列/索引中使用指定的编码对字符串进行编码。相当于str.encode()。
语法:
Series.str.encode(encoding, errors=’strict’)
参数:
encoding: str
errors: str, optional
返回: 编码:系列/索引的对象
示例#1:使用Series.str.encode()函数对给定系列对象的底层数据中存在的字符串进行编码。使用’raw_unicode_escape’进行编码。
# importing pandas as pd
import pandas as pd
# Creating the Series
sr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich'])
# Creating the index
idx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']
# set the index
sr.index = idx
# Print the series
print(sr)
输出 :
现在我们将使用Series.str.encode()函数对给定系列对象的基础数据中存在的字符串进行编码。
# use 'raw_unicode_escape' encoding
result = sr.str.encode(encoding = 'raw_unicode_escape')
# print the result
print(result)
输出 :
正如我们在输出中看到的,Series.str.encode()函数已经成功地对给定系列对象中的字符串进行了编码。
示例#2 :使用Series.str.encode()函数对给定系列对象的基础数据中存在的字符串进行编码。使用’punycode’进行编码。
# importing pandas as pd
import pandas as pd
# Creating the Series
sr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney'])
# Creating the index
idx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5']
# set the index
sr.index = idx
# Print the series
print(sr)
输出 :
现在我们将使用Series.str.encode()函数对给定系列对象的基础数据中存在的字符串进行编码。
# use 'punycode' encoding
result = sr.str.encode(encoding = 'punycode')
# print the result
print(result)
输出 :
正如我们在输出中看到的,Series.str.encode()函数已经成功地对给定系列对象中的字符串进行了编码。