python decode函数的用法_Python Pandas Series.str.decode()用法及代码示例

Series.str可用于以字符串形式访问系列的值并对其应用几种方法。 Pandas Series.str.decode()函数用于使用指示的编码来解码系列/索引中的字符串。此功能等效于str.decode()在python2和bytes.decode()在python3中。

用法: Series.str.decode(encoding, errors=’strict’)

参数:

encoding:str

errors:str,可选

返回:解码的对象序列/索引

范例1:采用Series.str.decode()函数解码给定系列对象的基础数据中的字符串。使用“ UTF-8”编码方法。

# importing pandas as pd

import pandas as pd

# Creating the Series

sr = pd.Series([b"b'New_York'", b"b'Lisbon'", b"b'Tokyo'", b"b'Paris'", b"b'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)

输出:

05feeba685debb16394a0901ba93c35d.png

现在我们将使用Series.str.decode()函数解码给定系列对象的基础数据中的字符串。

# use 'UTF-8' encoding

result = sr.str.decode(encoding = 'UTF-8')

# print the result

print(result)

输出:

670e60629ee1e0c3f9079df75c3d8e9b.png

正如我们在输出中看到的,Series.str.decode()函数已成功解码给定系列对象的基础数据中的字符串。

范例2:采用Series.str.decode()函数解码给定系列对象的基础数据中的字符串。使用“ ASCII”编码方法。

# importing pandas as pd

import pandas as pd

# Creating the Series

sr = pd.Series([b'Mike-', b'Alessa-', b'Nick-', b'Kim-', b'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)

输出:

c808b6231408956ac4552f363fbf7ea7.png

现在我们将使用Series.str.decode()函数解码给定系列对象的基础数据中的字符串。

# use 'ASCII' encoding

result = sr.str.decode(encoding = 'ASCII')

# print the result

print(result)

输出:

1e935fdc515fd7493d1629a49dce9382.png

正如我们在输出中看到的,Series.str.decode()函数已成功解码给定系列对象的基础数据中的字符串。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值