如何返回具有最高计数值“ GPE”的列名?在这种情况下,我希望输出只是“文本”,因为该列具有两行“ GPE”,而text2列为1,text3列为0。
代码:
import spacy
import pandas as pd
import en_core_web_sm
nlp = en_core_web_sm.load()
text = [["Canada", 'University of California has great research', "non-location"],["China", 'MIT is at Boston', "non-location"]]
df = pd.DataFrame(text, columns = ['text', 'text2', 'text3'])
col_list = df.columns # obtains the columns of the dataframe
for col in col_list:
df["".join(col)] = df[col].apply(lambda x: [[w.label_] for w in list(nlp(x).ents)]) # combine the ent_<<col_name>> as the new columns which contain the named entities.
df
所需的输出:
text
答案 0 :(得分:2)
您可以使用values_count()
。
您的代码应如下所示:
import spacy
import pandas as pd
import en_core_web_sm
nlp = en_core_web_sm.load()
text = [["Canada", 'University of California has great research', "non-location"],["China", 'MIT is at Boston', "non-location"]]
df = pd.DataFrame(text, columns = ['text', 'text2', 'text3'])
col_list = df.columns # obtains the columns of the dataframe
maxGPE = 0
index = ''
for col in col_list:
newGPE = df[col].apply(lambda x: x in nlp(x).ents).sum()
if newGPE > maxGPE:
index = col
maxGPE = newGPE
print(index)