【问题标题】:Create new columns based on an existing column. Use 1 or 0基于现有列创建新列。使用 1 或 0
【发布时间】:2020-12-23 08:11:12
【问题描述】:

这是数据框:

我想以二进制格式添加 4 个新列(“business_trip”、“leisure”、“group”、“couple”。如果该行包含“出差”,然后在“business_trip”列中为该行输出 1,如果不是输出 0。其他列的逻辑相同。这是预期的输出:

【问题讨论】:

标签: python dataframe for-loop split conditional-statements


【解决方案1】:

其实我自己想出了以下解决方案,如果您有其他更好的解决方案,请告诉我。谢谢!

from re import search

def tags(data, tag):
    data[tag] = data['Review_tags'].apply(lambda x: 1 if search(tag, x) else 0)
    return data

tags(df, 'Leisure')
tags(df, 'Business')
tags(df, 'Couple')
tags(df, 'Group')

【讨论】:

  • 我找到了另一种方法! data[tag] = data['Review_tags'].str.count(tag)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-12
  • 2014-01-04
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-07
相关资源
最近更新 更多