【问题标题】:Pandas DataFrame: remove � (unknown-character) from strings in rowsPandas DataFrame:从行中的字符串中删除 �(未知字符)
【发布时间】:2017-07-13 10:06:16
【问题描述】:

我已将 csv 文件读入 python 2.7(Windows 机器)。销售价格列似乎是字符串和浮动的混合体。有些行包含欧元符号€。 Python 将 € 视为 �。

df = pd.read_csv('sales.csv', thousands=',')
print df

Gender  Size    Color   Category    Sales Price
Female  36-38   Blue    Socks       25
Female  44-46   Pink    Socks       13.2
Unisex  36-38   Black   Socks      � 19.00
Unisex  40-42   Pink    Socks      � 18.50
Female  38      Yellow  Pants      � 89,00
Female  43      Black   Pants      � 89,00

我假设一个简单的替换行就可以解决它

df=df.replace('\�','',regex=True).astype(float)

但是我得到了编码错误

SyntaxError: Non-ASCII character

希望听到您对此的看法

【问题讨论】:

  • df = pd.read_csv('sales.csv', thousands=',', encoding='utf-8')df = pd.read_csv('sales.csv', thousands=',', encoding='latin') 是如何工作的?
  • 它们都不起作用,同样的错误
  • 尝试使用chardet 实用程序查找编码,然后在pandas 参数中指定它。

标签: pandas encoding non-ascii-characters


【解决方案1】:

我认为@jezrael 的评论是有效的。首先你需要读取带有编码的文件(参见编码部分下的https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html

df=pd.read_csv('sales.csv', thousands=',', encoding='utf-8')

但是要替换欧元符号试试这个:

df=df.replace('\u20AC','',regex=True).astype(float)

【讨论】:

    【解决方案2】:

    我遇到了类似的问题,我的数据框中的一列有很多货币符号。欧元、美元、日元、英镑等。我尝试了多种解决方案,但最简单的一种是使用unicodedata 模块。

    df['Sales Price'] = df['Sales Price'].str.replace(unicodedata.lookup('EURO SIGN'), 'Euro')
    

    以上将在Sales Price 列中将 替换为Euro

    【讨论】:

      猜你喜欢
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 2017-03-18
      • 1970-01-01
      • 2020-10-12
      相关资源
      最近更新 更多