【问题标题】:Pandas convert object column to str - column contains unicode, float etcPandas 将对象列转换为 str - 列包含 unicode、float 等
【发布时间】:2018-01-09 22:29:08
【问题描述】:

我有 pandas 数据框,其中列类型显示为 object 但是当我尝试转换为字符串时,

df['column'] = df['column'].astype('str')

UnicodeEncodeError 被抛出: *** UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)

我的下一个方法是处理编码部分: df['column'] = filtered_df['column'].apply(lambda x: x.encode('utf-8').strip())

但这会产生以下错误: *** AttributeError: 'float' object has no attribute 'encode'

将此列转换为字符串的最佳方法是什么。

列中的字符串示例

Thank you :)
Thank You !!!
responsibilities/assigned job.

【问题讨论】:

  • 您仍然可以将 str.accessors 与对象列一起使用。试试:df['column'].str.encode('utf-8').str.decode('latin-1').astype(str)
  • 试过但给了我*** UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-11: ordinal not in range(128)
  • 我想看看一些数据。请看看你是否可以用一些玩具数据来重现这个。

标签: python-2.7 pandas utf-8


【解决方案1】:

在尝试运行最初用于 python 3 的脚本时,我在 python 2.7 中遇到了同样的问题。在 python 2.7 中,默认的 str 功能是编码为 ASCII,这显然不适用于您的数据。这可以用一个简单的例子来复制:

import pandas as pd
df = pd.DataFrame({'column': ['asdf', u'uh ™ oh', 123]})
df['column'] = df['column'].astype('str')

结果:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 3: ordinal not in range(128)

相反,您可以指定 unicode:

df['column'] = df['column'].astype('unicode')

验证数字是否已转换为字符串:

df['column'][2]

这会输出u'123',因此它已被转换为Unicode 字符串。特殊字符 ™ 也已妥善保存。

【讨论】:

  • 这个答案被生命拯救了。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-13
  • 2021-05-25
  • 2019-07-26
  • 1970-01-01
  • 2022-12-23
  • 2018-11-23
  • 2014-09-30
相关资源
最近更新 更多