Pandas:添加新列有困难

2024-09-28 22:32:03 发布

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

我有一个Pandas数据帧numeric_df,有一堆列。我有这个功能:

def textstat_stats(text):
    difficulty = textstat.flesch_reading_ease(text)
    grade_difficulty = textstat.flesch_kincaid_grade(text)
    gfog = textstat.gunning_fog(text)
    smog = textstat.smog_index(text)
    ari = textstat.automated_readability_index(text)
    cli = textstat.coleman_liau_index(text)
    lwf = textstat.linsear_write_formula(text)
    dcrs = textstat.dale_chall_readability_score(text)
    return pd.Series([difficulty, grade_difficulty, gfog, smog, ari, cli, lwf, dcrs])

返回熊猫系列。现在我试着这样做:

numeric_df[['difficulty', 'grade_difficulty','gfog','smog','ari','cli','lwf','dcrs']] = textstat_stats(text)

但是,我得到一个错误:

KeyError: "['difficulty' 'grade_difficulty' 'gfog' 'smog' 'ari' 'cli' 'lwf' 'dcrs'] not in index"

我做错了什么?你知道吗

谢谢!你知道吗


Tags: textdfindexclistatsgradearinumeric
1条回答
网友
1楼 · 发布于 2024-09-28 22:32:03

似乎需要向Series添加索引,该索引创建列名称:

def textstat_stats(text):
    difficulty = textstat.flesch_reading_ease(text)
    grade_difficulty = textstat.flesch_kincaid_grade(text)
    gfog = textstat.gunning_fog(text)
    smog = textstat.smog_index(text)
    ari = textstat.automated_readability_index(text)
    cli = textstat.coleman_liau_index(text)
    lwf = textstat.linsear_write_formula(text)
    dcrs = textstat.dale_chall_readability_score(text)
    idx = ['difficulty', 'grade_difficulty','gfog','smog','ari','cli','lwf','dcrs']
    return pd.Series([difficulty, grade_difficulty, gfog, smog, ari, cli, lwf, dcrs], 
                     index=idx)

df = textstat_stats(text)
print (df)

相关问题 更多 >