首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在DataFrame中组合行

在DataFrame中组合行
EN

Stack Overflow用户
提问于 2018-06-02 21:07:06
回答 2查看 55关注 0票数 1

我有一个具有NER分类器结果的DF,如下所示:

代码语言:javascript
复制
df =

s        token        pred       tokenID
17     hakawati       B-Loc         3
17     theatre        L-Loc         3
17     jerusalem      U-Loc         7
56     university     B-Org         5
56     of             I-Org         5
56     texas          I-Org         5
56     here           L-Org         6
...
5402   dwight         B-Peop        1    
5402   d.             I-Peop        1
5402   eisenhower     L-Peop        1  

此DataFrame中还有许多其他不相关的列。现在,我想根据它们的sentenceID (=s)和它们的预测标签对这些标记进行分组,以将它们组合成一个实体:

代码语言:javascript
复制
df2 =


s        token                        pred               
17     hakawati  theatre           Location
17     jerusalem                   Location
56     university of texas here    Organisation
...
5402   dwight d. eisenhower        People

通常,我只需使用像data_map = df.groupby(["s"],as_index=False, sort=False).agg(" ".join)这样的行并使用重命名函数即可。然而,由于数据包含不同类型的字符串(B、I、L-Loc/Org.)我不知道该怎么做。

任何想法都是值得感谢的。

有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-02 21:37:02

一种通过辅助列的解决方案。

代码语言:javascript
复制
df['pred_cat'] = df['pred'].str.split('-').str[-1]

res = df.groupby(['s', 'pred_cat'])['token']\
        .apply(' '.join).reset_index()

print(res)

      s pred_cat                       token
0    17      Loc  hakawati theatre jerusalem
1    56      Org    university of texas here
2  5402     Peop        dwight d. eisenhower

注意,这并不完全匹配您想要的输出;似乎涉及到一些特定于数据的处理。

票数 1
EN

Stack Overflow用户

发布于 2018-06-02 21:28:34

您可以同时按stokenID进行分组,并按如下方式聚合:

代码语言:javascript
复制
def aggregate(df):
    token = " ".join(df.token)
    pred = df.iloc[0].pred.split("-", 1)[1]
    return pd.Series({"token": token, "pred": pred})

df.groupby(["s", "tokenID"]).apply(aggregate)

# Output
                             token  pred
s    tokenID                            
17   3            hakawati theatre   Loc
     7                   jerusalem   Loc
56   5         university of texas   Org
     6                        here   Org
5402 1        dwight d. eisenhower  Peop
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50657239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档