Skip to main content
 首页 » 编程设计

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

2024年09月07日7虾米哥

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

             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_dummies 与 pd.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_value 和 astype(bool) 用于匹配 OP 输出。我使用 drop 和 join(df.Result) 作为将 Result 放到数据帧末尾的简洁方法。