У меня есть данные в CSV-файле, который выглядит так
sent_num = [0, 1, 2]
text = [['Jack', 'in', 'the', 'box'], ['Jack', 'in', 'the', 'box'], ['Jack', 'in', 'the', 'box']]
tags = [['B-ORG', 'I-ORG', 'I-ORG', 'I-ORG'], ['B-ORG', 'I-ORG', 'I-ORG', 'I-ORG'], ['B-ORG', 'I-ORG', 'I-ORG', 'I-ORG']]
df = pd.DataFrame(zip(sent_num, text, tags), columns=['sent_num', 'text', 'tags'])
df
Я хочу преобразовать эти данные в текстовый файл формата CoNLL, как показано ниже, где каждый столбец (текст и теги) разделен табуляцией, а конец каждого предложения (или документа) обозначен пустой строкой.
text tags
Jack B-ORG
in I-ORG
the I-ORG
box I-ORG
Jack B-ORG
in I-ORG
the I-ORG
box I-ORG
Jack B-ORG
in I-ORG
the I-ORG
box I-ORG
То, что я пробовал, но не сработало, считает пустые строки действительными данными, а не концом предложения.
# create a three-column dataset
DF = df.apply(pd.Series.explode)
DF.head()
# insert space between rows in the data frame
# find the indices where changes occur
switch = DF['sent_num'].ne(DF['sent_num'].shift(-1))
# construct a new empty dataframe and shift index by .5
DF1 = pd.DataFrame('', index=switch.index[switch] + .1, columns=DF.columns)
# concatenate old and new dataframes and sort by index, reset index and remove row positions by iloc
DF2 = pd.concat([DF, DF1]).sort_index().reset_index(drop=True).iloc[:-1]
DF2.head()
group by tags
DF2[['text', 'tags']].groupby('tags').count()
Мне нужна помощь в изменении или улучшении имеющегося у меня кода.