首页 > 解决方案 > 从充满混乱的字符串列中获取虚拟变量

问题描述

我是 Python 和数据科学的不到一周的初学者,所以如果这些问题看起来很明显,请原谅我。

我已经在网站上抓取了数据,但不幸的是,结果的格式不是很好,我不能在没有转换的情况下使用它。

我的资料

我有一个字符串列,其中包含许多我想转换为虚拟变量的特征。

字符串示例:“8 équipements & optionsextérieur et châssisjantes aluintérieurBluetoothfermeture électrique5 placessécuritékit téléphone main libre bluetoothABSautreAPPUI TETE ARclimatisation”

我想做什么

我想创建一个虚拟列“蓝牙”,如果字符串中包含模式“蓝牙”,则该列等于一,否则为零。

我想创建另一个虚拟列“Climatisation”,如果字符串中包含模式“climatisation”,则该列等于 1,否则为零。

...ETC

并针对我感兴趣的 5 或 6 个模式进行操作。

我试过的

我想使用带有正则表达式的匹配测试并将其与 pd.getdummies 方法结合使用。

import re
import pandas as pd

def match(My_pattern,My_strng):
    m=re.search(My_pattern,My_strng)
    if m:
        return True
    else:
        return False

pd.getdummies(df["My messy strings colum"], ...)

我还没有成功找到如何解决 pd.getdummies 参数来指定我想在列上应用的测试。

我什至想知道这是否是最好的策略,以及是否更容易创建其他平行列并在我凌乱的字符串上应用 match.group() 来填充它们。不确定我是否会知道如何编程。

谢谢你的帮助

标签: pythonregexpandasdummy-variable

解决方案


我认为这样做的一种方法是:

df.loc[df['My messy strings colum'].str.contains("bluetooth", na=False),'Bluetooth'] = 1
df.loc[~(df['My messy strings colum'].str.contains("bluetooth", na=False)),'Bluetooth'] = 0

df.loc[df['My messy strings colum'].str.contains("climatisation", na=False),'Climatisation'] = 1
df.loc[~(df['My messy strings colum'].str.contains("climatisation", na=False)),'Climatisation'] = 0

波浪号 (~) 表示not,因此在这种情况下,条件反转为字符串不包含

na = false 表示如果您的凌乱列包含任何空值,这些都不会导致错误,只是假定它们不满足条件。


推荐阅读