当我向 DataFrame 添加新帖子时,我目前只是根据帖子 ID 删除重复项,但我想向我的 DataFrame 添加一个“评论”列,该列将是一个包含另一个 DataFrame 中评论 ID 的列表。
问题是这样的,如果帖子有新评论,我希望它要么将新评论添加到评论列,要么用现在有新评论的帖子替换整行。
这是一些代码来说明我的问题:
posts = pd.DataFrame(data, columns=['ID', 'Date/Time', 'Title', 'Body', 'Comments'])
new_posts = get_new_posts() # Returns DataFrame containing new posts
pd.concat([posts, new_posts], ignore_index=True).drop_duplicates('ID')
我想做的是这样的事情(我知道这是行不通的)
posts = pd.DataFrame(data, columns=['ID', 'Date/Time', 'Title', 'Body', 'Comments'])
new_posts = get_new_posts() # Returns DataFrame containing new posts
pd.concat([posts, new_posts], ignore_index=True).drop_duplicates(if 'ID' and 'Comments' else replace row)
我不能只是简单地删除重复项,因为据我所知,这会保留旧帖子,同时添加带有更新评论但 ID 相同的新帖子
ID
和
Date/Time
按降序对 DataFrame 进行排序,然后根据
ID
删除重复项:
posts = pd.DataFrame(data, columns=['ID', 'Date/Time', 'Title', 'Body', 'Comments'])
new_posts = get_new_posts()
all_posts = pd.concat([posts, new_posts], ignore_index=True)
all_posts.sort_values(by=['ID', 'Data/Time'], ascending=[True, False], inplace=True)
all_posts.drop_duplicates(subset='ID', keep='first', inplace=True)