python - 从充满混乱的字符串列中获取虚拟变量
问题描述
我是 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() 来填充它们。不确定我是否会知道如何编程。
谢谢你的帮助
解决方案
我认为这样做的一种方法是:
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 表示如果您的凌乱列包含任何空值,这些都不会导致错误,只是假定它们不满足条件。
推荐阅读
- css - 反应,引导导航
- wireshark - 带有 Libpcap(或 WinPcap)的 Wireshark 可移植(无管理员权限)
- python - 函数多次运行时,列表嵌套在默认参数中,但整数不是
- excel - 尝试使用 VBA 对工作表范围进行排序 - 升序有效但不降序
- flutter - 乳胶不使用canvaskit颤振渲染
- kotlin - 以某种方式组合抽象类?
- wordpress - 联系表格 7:带有自定义文件上传按钮的邮件标签
- javascript - 如何降低字体大小以适应 div 中的新用户数字
- javascript - 淘汰赛 Js 多选绑定
- python - 在二维 Numpy 数组中查找最近的元素