追加时在熊猫中保留唯一索引(或ID)

时间:2019-09-12 10:25:06

标签: python pandas

我想在pandas DataFrame中添加新行。而且,我想有另一个引用第一个的DataFrame。 例如,我有一个包含新闻的表格,每一行都是唯一的新闻,例如

pd.DataFrame.from_dict({0: ['company1 is bankrupt'],
                        1: ['company2 and company3 are going to merge. company1 is good'],
                        2: ['company3 is going to create a new product. CEO of company3 says it will be a good product']}, orient='index', columns=['text'])

我还想保留有关每个新闻中的公司以及每个新闻出现在文本中的次数的信息。我想创建一个新的数据框,例如:

index company  freq    
news1 company1 2  
news1 company2 1   
news2 company3 3  

...
但是要做到这一点,我需要有一个新闻的稳定ID,但是如果要追加,则需要重新编制索引。如果我在中间删除了一条新闻,则重新索引ID将被更改,因此追加新行可以更改我的ID,因此我无法引用此ID。我该怎么办?也许我应该在数据框中创建一个数据框(或字典)来摆脱这个问题?

1 个答案:

答案 0 :(得分:0)

为什么不像您所说的那样简单地为新闻创建ID?它不需要在索引中。只需:

df['news_id'] = [i for i in range(len(df))]

这将为每个新闻附加一个ID(可能与您的索引重复)。现在,您只需在附加行中引用news_id,而不必担心索引。

编辑:如果您要定期更新数据库,则可以简单地使用更复杂的ID创建器。像这样:

import random
characters = 'abcdefghijklmnopqrstuvwxyz123456789'
used_ids = []
def pick_id():
    global used_ids #this allows us to use and modify the used_ids list in the function
    ID = ''.join([random.choice(characters) for i in range(16)]) #arbitrary length of 16 for IDs
    while ID in used_ids: #this simply repeats the generation of IDs if the ID is already in used_ids
        ID = ''.join([random.choice(characters) for i in range(16)])
    used_ids.append(ID) #now add the used ID to used_ids
    return ID

现在您可以轻松地做到:

df['news_id'] = [pick_id() for i in range(len(df))]

这需要您跟踪news_id,但还不错:只要运行此程序,您就可以像这样读取新的数据框:

used_ids = list(set(list(new_dataframe['news_id'])))

这将为您提供所有已经使用的唯一ID。