我有一个具有NER分类器结果的DF,如下所示:
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)和它们的预测标签对这些标记进行分组,以将它们组合成一个实体:
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.)我不知道该怎么做。
任何想法都是值得感谢的。
有什么想法吗?
发布于 2018-06-02 21:37:02
一种通过辅助列的解决方案。
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
注意,这并不完全匹配您想要的输出;似乎涉及到一些特定于数据的处理。
发布于 2018-06-02 21:28:34
您可以同时按s
和tokenID
进行分组,并按如下方式聚合:
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
https://stackoverflow.com/questions/50657239
复制相似问题