【问题标题】:how to add a value to the end of a pandas column without index如何在没有索引的熊猫列的末尾添加一个值
【发布时间】:2021-10-30 03:58:25
【问题描述】:

我有一个数据框,我想在其中的列末尾添加值,不使用索引,因为我在对象内执行此操作, 由于某种原因,pandas append 对我不起作用,我尝试直接将其添加到另一个数据框中(代码中的 x)。 我想要类似的东西:

DB=pd.DataFrame(columns=['reviews'])
DB= DB.append(object)# append to reviews column, reviews is also an object 

但是当我这样做时,我得到了错误:

UnboundLocalError: local variable 'DB' referenced before assignment

我期待得到类似的东西:

    reviews
0  <__main__.Review object at 0x0000020D2A14BD48>
1  <__main__.Review object at 0x0000020D29F17D88>

我的代码是这样的:

DB=pd.DataFrame(columns=['reviews'])

class Review:

    def __init__(self, json_string):
       self.json_string=json_string

    def get_text(self):
       json_dict=json.loads(self.json_string)
       return json_dict['body']



class ReviewSearchEngine:

    def __init__(self):
       pass

    def add(self, review:Review):
      
        x = pd.DataFrame(columns=['reviews'])
        x.loc[0, 'reviews'] = review
        ****DB= DB.append(x)****
        return
if __name__ == '__main__':

    search_engine = ReviewSearchEngine()
    file_path = "./review_data.txt"  
    lines = open(file_path).readlines()
    for line in lines:
       review = Review(line) # review is an object
       search_engine.add(review)



 

【问题讨论】:

  • DB 在类之外定义。您应该在 __init__ 的类中定义它
  • 您能提供一个示例输出吗?它是您尝试在评论列中附加的字符串吗?例如,将名称附加到“评论”?
  • 谢谢,它正在工作(当我实际上将它添加到属性中时)但现在我为来自 x 的所有评论获取索引 0,当我尝试 DB.append(reviews) 时,我得到一个错误。所以我遇到了同样的问题,没有任何方法可以作为列表工作吗?
  • 在上面的问题中添加

标签: python pandas object indexing append


【解决方案1】:

我建议你试试这个:

class Review:

    def __init__(self, json_string):
        self.json_string = json_string

    def get_text(self):
        json_dict = json.loads(self.json_string)
        return json_dict['body']


class ReviewSearchEngine:

    def __init__(self, db):
        self.db = db

    def add(self, review: Review):
        x = pd.DataFrame(columns=['reviews'])
        x.loc[0, 'reviews'] = review
        self.db = self.db.append(x, ignore_index=True)


if __name__ == '__main__':
    DB = pd.DataFrame(columns=['reviews'])

    search_engine = ReviewSearchEngine(DB)
    file_ = "stack.txt"
    lines = open(file_).readlines()
    for line in lines:
        review = Review(line)  # review is an object
        search_engine.add(review)
    print(search_engine.__dict__['db'])

>>>                                       reviews
0  <__main__.Review object at 0x000001B497563400>
1  <__main__.Review object at 0x000001B4975634F0>
2  <__main__.Review object at 0x000001B49754DEE0>

请在方法pd.DataFrame.append时指定参数ignore_index=True以避免意外索引。

【讨论】:

    猜你喜欢
    • 2021-08-24
    • 2021-11-17
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 2023-01-17
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多