基于现有列创建新列。使用1或0

2024-05-20 06:48:20 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是数据帧:

enter image description here

我想以二进制格式添加4个新列(“商务旅行”、“休闲”、“团体”、“情侣”“情侣”)。如果该行包含“商务旅行”,则在“商务旅行”列中为该行输出1,如果不输出0。其他列的逻辑相同。以下是预期的输出:

enter image description here


Tags: 数据格式二进制逻辑团体情侣
1条回答
网友
1楼 · 发布于 2024-05-20 06:48:20

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

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')

enter image description here

相关问题 更多 >