【问题标题】:Get dummy variables from a string column full of mess从充满混乱的字符串列中获取虚拟变量
【发布时间】:2020-04-10 10:29:21
【问题描述】:

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

我在一个网站上抓取了数据,但很遗憾,结果的格式不是很好,如果不进行转换,我将无法使用它。

我的数据

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

字符串示例:“8 个设备和选项extérieur et châssisjantes aluintérieurBluetoothfermeture électrique5 placessécuritékit téléphone main libre bluetoothABSautreAPPUI TETE ARclimatisation”

我想做的事

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

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

...等

并针对我感兴趣的 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['bluetooth'] = df['column'].str.contains('Bluetooth').astype(int)
  • 非常感谢,在填充了所有 NaN 元素后,它就可以工作了。

标签: python regex pandas dummy-variable


【解决方案1】:

我认为一种方法是:

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

波浪号(~)代表,所以本例中的条件反转为字符串不包含

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

【讨论】:

  • 谢谢,它也很有效,并引起了我对 NaN 问题的关注。
  • 当然可以,但是很抱歉,我不知道该怎么做。我在哪里可以做到这一点?
  • 你会看到我的答案旁边有一个灰色的小勾,一旦点击就会变成绿色
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
  • 2015-05-20
相关资源
最近更新 更多