Pandas 在行中查找文本并基于此分配一个虚拟变量值

edyvedy13

我有一个包含文本列的数据框,df["input"]

我想创建一个新变量,它检查df["input"]列是否包含给定列表中的任何单词,如果先前的虚拟变量等于 0(逻辑为 1),则分配值 1(逻辑为 1)创建一个等于零的虚拟变量 2)如果它包含给定列表中的任何单词并且它不包含在以前的列表中,则将其替换为一个。)

# Example lists
listings = ["amazon listing", "ecommerce", "products"]
scripting = ["subtitle",  "film", "dubbing"]
medical = ["medical", "biotechnology", "dentist"]

df = pd.DataFrame({'input': ['amazon listing subtitle', 
                             'medical', 
                             'film biotechnology dentist']})

看起来像:

input
amazon listing subtitle
medical 
film biotechnology dentist

最终数据集应如下所示:

input                           listings  scripting  medical
amazon listing subtitle            1         0         0
medical                            0         0         1          
film biotechnology dentist         0         1         0
寡妇

一种可能的实现是str.contains在循环中使用来创建 3 列,然后用于idxmax获取第一个匹配项的列名(或列表名),然后从这些匹配项中创建一个虚拟变量:

import numpy as np
d = {'listings':listings, 'scripting':scripting, 'medical':medical}
for k,v in d.items():
    df[k] = df['input'].str.contains('|'.join(v))

arr = df[list(d)].to_numpy()
tmp = np.zeros(arr.shape, dtype='int8')
tmp[np.arange(len(arr)), arr.argmax(axis=1)] = arr.max(axis=1)
out = pd.DataFrame(tmp, columns=list(d)).combine_first(df)

但在这种情况下,使用嵌套的 for 循环可能更有效:

import re
def get_dummy_vars(col, lsts):
    out = []
    len_lsts = len(lsts)
    for row in col:
        tmp = []
        # in the nested loop, we use the any function to check for the first match 
        # if there's a match, break the loop and pad 0s since we don't care if there's another match
        for lst in lsts:
            tmp.append(int(any(True for x in lst if re.search(fr"\b{x}\b", row))))
            if tmp[-1]:
                break
        tmp += [0] * (len_lsts - len(tmp))
        out.append(tmp)
    return out

lsts = [listings, scripting, medical]
out = df.join(pd.DataFrame(get_dummy_vars(df['input'], lsts), columns=['listings', 'scripting', 'medical']))

输出:

                        input listings medical scripting
0     amazon listing subtitle        1       0         0
1                     medical        0       1         0
2  film biotechnology dentist        0       0         1

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将变量值分配给 Pandas DataFrame 中的新列

如何在 JavaScript 中为新的变量值分配一个变量值

通过另一列中的变量值将pandas数据框列移位

SAS-基于表中另一个变量值的变量值的倒序

查找作为参数传递的变量值并替换为 Bash 脚本中的另一个变量值

如何导入多个csv,分配变量并使用Pandas concat连接到一个DataFrame中?

使用Python Pandas df.loc查找部分变量值

如何将列与 Pandas 中的虚拟变量组合在一起(一个输出)?

pandas:从基于列的另一个数据帧中查找每列的记录并除以标量

在行包含多个变量作为列表的Pandas中获取虚拟变量?

Pandas 中的重复测量方差分析,不同列中的因变量值

根据Bash中尚不存在的另一个变量分配变量值

如何在Pandas SQL查询中动态传递变量值

在Pandas数据框中传递字符串变量值

Python Pandas 在一个基于另一个 df 的 df 中删除行

R:基于另一个变量的因子水平的新变量值

如何在shell脚本中将一个变量值分配给另一个变量

如何分配一个新列,其中值是一组基于pandas的多列的列名?

两个变量的并集以在Pandas Data Frame中形成一个新变量-Python

Python Pandas 在列中求和一个常量值如果日期介于 2 个日期之间

Pandas Dataframe 使用 groupby 另一个列值对列中的每 2 个增量值进行排名

根据另一个类上的变量值设置Qlabel文本

在另一个变量中插入一些变量值

如何从组件中获取变量值并将其分配给 vuejs 中另一个组件中的变量

如何将变量值放在javascript中的另一个变量中?

通过存储在Powershell中另一个变量中的名称获取变量值

如何基于Pandas中的另一个DataFrame更改DataFrame的某些列中的值

如何基于另一个 DataFrame 中的列在 Pandas DataFrame 中创建新列?

将 pd.series 中的 Pandas 中的列名分配给一个循环