【问题标题】:Python Convert Pandas Float to StringPython 将 Pandas 浮点数转换为字符串
【发布时间】:2014-09-04 13:53:08
【问题描述】:

您有一个数据框 (df),其中包含从 Excel 电子表格读取到 Python/Pandas 的两列(日期、文本)。

xl = pd.ExcelFile(dir+"file.xlsx")
df = xl.parse(xl.sheet_names[0])

    date        text                
0   2013-08-06  NaN                 
1   2013-08-06  Text with unicode
2   ...

文本包含不需要的 unicode 字符,我通常会使用这些字符将其删除

df['text'] = df['text'].apply(lambda sentence: ''.join(word for word in sentence if ord(word) < 128))

但是,由于第一行中的文本包含“NaN”,因此 Pandas 似乎将该列键入为“float”,并且上述命令失败,因为它只对字符串进行操作。我找不到将类型重新分配为字符串的方法,因为它包含 unicode 字符:

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

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-12: ordinal not in range(128) 

感觉就像我陷入了“先有鸡还是先有蛋”的困境。

【问题讨论】:

  • 你能把你用来阅读电子表格的那一行写进去吗?
  • 你不能只打电话给dropna 或者你想用一些值替换NaN 吗?
  • @chrisaycock:我添加了用于阅读电子表格的行。
  • @EdChum:如果我 dropna,我假设 Pandas 仍然将该列视为浮点数。我仍然无法将其转换为字符串类型,因为它包含 unicode。
  • 我和你不一样,我的是object,这是一个string,我不明白你怎么会有这样的dtype。仍然在删除 NaN 之后,您应该可以使用 astype(float) 进行投射

标签: python unicode pandas ipython


【解决方案1】:

这不是您将整列输入为浮点数的 - 否则它根本无法保存字符串。只是 NaN 值导致您的方法抛出异常。

所以您必须处理 NaN - 您希望您的代码如何转换 NaN?到'NaN'?

这种将NaN作为特殊值的点。如果您不想要 NaN 值 - 您可以使用 dropna。如果您想要其他值(或字符串值) - 您可以使用 .fillna('NaN')。如果您想保留 NaN 以供将来使用(这对我来说似乎是要走的路)-只需在您的 lambda 中为它们设置一个特殊情况,这将使它们保持为 NaN:

from pandas import isnull
lambda sentence: sentence if isnull(sentence) else \
                          ''.join(word for word in sentence if ord(word) < 128)

【讨论】:

  • 如博文所述,目前文字类型为“float”,需要先转换为“string”类型。但是,由于文本中不需要的 unicode,我无法将文本转换为字符串。
  • @slaw 你如何在问题中发布一些真实数据。
猜你喜欢
  • 2022-01-10
  • 2011-11-25
  • 2019-07-10
  • 2018-08-23
  • 2017-11-29
  • 1970-01-01
  • 1970-01-01
  • 2019-10-03
相关资源
最近更新 更多