gpt4 book ai didi

python - 执行添加列并根据 Pandas 中的其他列填充它们的函数

转载 作者:太空宇宙 更新时间:2023-11-04 02:31:00 25 4
gpt4 key购买 nike

我有一个包含文本和结果的数据框

             Text    Result
0 some text... True
1 another one... False

我有一个函数可以从文本中提取特征 - 返回包含大约 1000 个单词键和 T/F 值的字典,具体取决于单词是否在文本中。

words = ["some", "text", "another", "one", "other", "words"]
def extract(text):
result = dict()
for w in words:
result[w] = (w in text)
return result

我期待的结果是

             Text    some   text  another one    other  words  Result
0 some text... True True False False False False True
1 another one... False False True True False False False

但我不知道如何将其应用于数据框?到目前为止我所做的是创建具有默认 False 值的列,但我不知道如何用 True 值填充它。

for feature in words:
df[feature] = False

我想在 pandas 中有更好的方法吗?

最佳答案

pd.Series.str.get_dummiespd.DataFrame.reindex 一起使用

exp = (
df.Text.str.get_dummies(' ')
.reindex(columns=words, fill_value=0)
.astype(bool)
)

df.drop('Result', 1).join(exp).join(df.Result)

Text some text another one other words Result
0 some text True True False False False False True
1 another one False False True True False False False

解释

get_dummies 为找到的每个单词提供虚拟列,非常简单。但是,我使用 reindex 来表示我们关心的所有单词。 fill_valueastype(bool) 用于匹配 OP 输出。我使用 dropjoin(df.Result) 作为将 Result 放到数据帧末尾的简洁方法。

关于python - 执行添加列并根据 Pandas 中的其他列填充它们的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49182255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com