【问题标题】:Create column input based on string input in Python function根据 Python 函数中的字符串输入创建列输入
【发布时间】:2020-06-23 09:30:28
【问题描述】:

所以我正在编写一个自定义函数,我希望将字符串输入转换为数据框,以便模型对其进行预测。现在我被困在编写一段代码,它能够检测输入字符串是否包含特定的单词,如果是,则将其处理到值为 1 或 0 的数据框列。但是,我无法要成功地纠正它,我怎样才能最好地解决这个问题? 这是我的一段代码:

def function(text_input)
    cols = ['col_foo', 'col_bar', 'col_hello', 'col_world']
    words = ['foo', 'bar', 'hello', 'world']
    data = [text_input.split()]
    for col in cols:
        df[col] = 0
    for word in data:
        if word in words:
           for words in cols:
               df[cols] = 1
    return df

我希望首先使用初始 0 值创建所有列。然后根据text_input中与words列表中的单词匹配的单词,将对应的cols设置为1个值。但是现在,这段代码输出了所有df[cols] = 0

我在这段代码中做错了什么?提前致谢!

【问题讨论】:

  • 查看你的代码然后你就会发现问题。
  • 我相信问题出在for words in cols: 行。由于添加了 col_ 名称,这不匹配。如何重写它以使其仅与列部分的实际名称匹配?
  • 使用cols,而不是words
  • 不太确定我是否明白你的意思。我在最后一部分中尝试做的是将值设置为 1 与匹配 text_input 中的单词的单词匹配的那些列
  • df[cols] --> df['col_foo', 'col_bar', 'col_hello', 'col_world']

标签: python string list function if-statement


【解决方案1】:

我想这就是你想要的:

def text_detecter(text_input): 
     df = pd.DataFrame({'foo':[0],'bar':[0],'hello':[0],'world':[0]}) 
     for col in df.columns: 
     df[col] = df[col].apply(lambda x: 1 if col in text_input else 0) 
     return df 

所以如果你再运行这个:

text_detecter('foo')

这将导致数据框:

     foo  bar  hello  world
0    1    0      0      0

【讨论】:

  • 是的,这确实很有意义。我唯一要添加的是为 col 名称添加前缀:col_ 如何添加?此外,如果它无法识别 text_input 中的单词,我仍然希望创建所有列并将其设置为 0。
  • def text_detecter(text_input): df = pd.DataFrame({'col_foo':[0],'col_bar':[0],'col_hello':[0],'col_world':[0]}) for col in df.columns: df[col] = df[col].apply(lambda x: 1 if col[4:] in text_input else 0) return df
  • 你可以像这样拥有它们,只需将 [4:] 添加到上述 for 循环中的 col 即可。
  • 不幸的是,我收到了 KeyError:'foo'。不确定是什么原因造成的,TraceBack 没有多大意义,因为这个函数内置在一个更大的函数中
  • 某处 foo 不是用作字符串,而是用作变量(因此可能没有 ' ' 围绕它),这会导致该错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-08
  • 1970-01-01
  • 1970-01-01
  • 2015-08-14
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
相关资源
最近更新 更多