【问题标题】:Creating a class to remove special characters in Python创建一个类以在 Python 中删除特殊字符
【发布时间】:2018-11-16 05:21:47
【问题描述】:

我想编写一个可以从我想要的数据框的任何列中删除特殊字符的类。例如,假设我有来自下表的数据:

Column A | Column B
?a?      | ?b?

我想退货:

Column A | Column B
  a      | b

我尝试编写一个类,以便从我从数据中选择的每一列中删除特殊字符。例如,如果我想删除“?”从 A 列开始,我希望能够为该特定列执行此操作。

class a():

    def __int__(self, col):
        self.col = col 

    def remove_char(self,col):
        for i, col in enumerate(df.col):
            df.iloc[:, i] = df.iloc[:, i].str.replace('?', '')
        return san_col


p = a()

san_data = p.remove_apost(df)

我收到一条错误消息,指出:

'NameError: name 'san_col' is not defined'

我对此较新,因此将不胜感激。

【问题讨论】:

  • 你从来没有在你的函数中定义san_col,因此不能返回它。
  • 为什么需要一个类?

标签: python python-3.x class


【解决方案1】:

问题是你从来没有定义过san_col 变量。

所以要解决它,(也让它变得更好):

class a:
    def __init__(self,df):
        self.df=df
    def remove_char(self):
        return self.df.replace('\?','',regex=True)

然后这样称呼它:

p = a(df)
print(p.remove_char())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    相关资源
    最近更新 更多