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

2024-04-24 08:59:58 发布

您现在位置:Python中文网/ 问答频道 /正文

请原谅,如果这个问题是太n00bish,我是全新的Python和需要使用它的工作,不幸的是,这意味着跳水到更高层次的东西没有首先了解的基础知识。。。你知道吗

我有一个巨大的CSV与文本抄本,我读到一个熊猫数据帧。这些转录本被分解成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”,我想它已经和文本或其他东西合并了。当我使用_frame()时,问题仍然存在。我想知道如何再次分离ID并使用它来索引数据?你知道吗


Tags: ofcsvthe数据代码文本idis
1条回答
网友
1楼 · 发布于 2024-04-24 08:59:58

groupby将返回groupbyed列作为索引。看看你的代码这就是我看到的。你知道吗

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.

相关问题 更多 >