【问题标题】:Apply class method to pandas dataframe column within other class method将类方法应用于其他类方法中的熊猫数据框列
【发布时间】:2022-10-04 16:03:36
【问题描述】:

我确信还有其他问题可以回答我的问题,但我找不到它们。所以,如果你知道它们,请把我重定向到那些。

我创建了一个类对象:

class Foo:

    def __init__(self, file_path: str, language = None):

        self.language = 'italian' if language is None else language


        # Assig to self object
        self.file_path = file_path
        self.file_type = file_path[-3:]

    def tweets_tokenizer(self, text):
     
        language = data_manager
        txt = word_tokenize(txt, language=self.language)
    
        return txt
        
    def get_dictionary(self):

        
        
        df = self.load() #I have a class method that loads the df, which I did not include in the 
                         #code here
        c_column = int(input(f'What is the index of the column containing the comments?'))
        comments = df.iloc[:, c_column]

        df['tokenized_comments'] =  df.iloc[:, c_column].apply(Foo.tweets_tokenizer)

      
        output = df.to_dict('index')
        

        return output

当我打电话时:

item = Foo('filepath')
d = item.get_dictionary()

我收到以下错误:

TypeError: tweets_tokenizer() missing 1 required positional argument: 'text'

哪个直接相关

df['tokenized_comments'] =  df.iloc[:, c_column].apply(Foo.tweets_tokenizer)

请注意,我在类中有其他静态方法,我可以成功应用它们而不会出现任何问题。但是,Foo.tweet_tokenize 方法不能设为静态,因为我需要传递语言参数。

【问题讨论】:

  • 要从内部引用一个类,您需要使用self,而不是foo

标签: python pandas


【解决方案1】:

您需要在 Foo 类中使用 self 调用 tweets_tokenizer 方法

df['tokenized_comments'] =  df.iloc[:, c_column].apply(self.tweets_tokenizer)

【讨论】:

    猜你喜欢
    • 2018-10-25
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    相关资源
    最近更新 更多