分组后数据框中的第一列丢失

first column in dataframe lost after grouping

如果这个问题太n00bish,请原谅,我是Python的新手,需要在工作中使用它,不幸的是,这意味着在没有先了解基础知识的情况下深入到更高层次的东西...

我有一个巨大的 CSV 文件,其中包含我读入 pandas 数据框的文本记录。这些转录本被分解为 ID,并且必须对 ID 进行分组以获得每次交互的单一记录,因为它们在它们来自的原始数据库中被分解为片段。格式是这样的:

    ID      TEXT
    1       This is the beginning of a convo
    1        heres the middle
    1       heres the end of the convo
    2       this is the start of another convo...etc.

我使用此代码按 ID 分组并创建单一记录:

    df1 = df.groupby('ID').text.apply(' '.join)

此代码运行良好,但现在我遇到了一系列(?)不再识别索引 "ID",我认为它已与文本或其他内容合并。当我使用 to_frame() 时,问题仍然存在。我想知道如何再次分离 ID 并使用它来索引数据?

groupby 将return groupby-ed 列作为索引。查看您的代码,这就是我所看到的。

import pandas as pd
df = pd.DataFrame({'ID':[1,1,1,2], 
                  'TEXT':['This is the beginning of a convo', 'heres the 
                          middle', 'heres the end of the convo', 'this is the 
                          start of another convo...etc.']})
df1 = df.groupby('ID').TEXT.apply(' '.join)
print(df1)

ID
1    This is the beginning of a convo heres the mid...
2    this is the start of another convo...etc.
Name: TEXT, dtype: object

如果您希望将 ID 作为数据框中的一列,您可以获取系列 df1 并为其重新编制索引,或者继续将其作为系列的索引,这可能会很方便,具体取决于什么你的下一步将是。

df1 = df1.reset_index()
print(df1)

    ID  TEXT
0   1   This is the beginning of a convo heres the mid...
1   2   this is the start of another convo...etc.