我有一个数据集,它有一个列(‘Facilities’),它的对象数据类型和几个缺失值,以及一个不带空格的字符串值.如下所示:

attachment

如何为它们增添空间?我try 了下面的一些代码,但不起作用:

X['Restaurant'] = X['facilities'].apply(lambda x: 1 if 'Restaurant' in x else 0)
X['BAR'] = X['facilities'].apply(lambda x: 1 if 'BAR' in x else 0)
X['SwimmingPools'] = X['facilities'].apply(lambda x: 1 if 'SwimmingPools' in x else 0)
df3 = X['facilities'].str.split(n=1, expand=True)
df3.columns = ['STATUS_ID{}'.format(x+1) for x in df3.columns]

推荐答案

您可以使用re.split将单词拆分成一个列表,然后使用空格作为分隔符对列表进行.join:

import pandas as pd
import re

df = pd.DataFrame({"facilities":["GymrestaurantbarInternetSwimmingPools",
                                "Poolrestaurantgyminternetbar",
                                "BARswimmingPoolsInternetgym"]})

#                               facilities
# 0  GymrestaurantbarInternetSwimmingPools
# 1           Poolrestaurantgyminternetbar
# 2            BARswimmingPoolsInternetgym

pattern = '(gym|restaurant|internet|swimmingpools|bar)' #Add all the words you want to separate by here 

df["facilities_cleaned"] = df.apply(lambda x: " ".join([word for word in re.split(pattern=pattern, string=x["facilities"].lower()) if len(word)>0]), axis=1)

#                               facilities                         facilities_cleaned
# 0  GymrestaurantbarInternetSwimmingPools  gym restaurant bar internet swimmingpools
# 1           Poolrestaurantgyminternetbar           pool restaurant gym internet bar
# 2            BARswimmingPoolsInternetgym             bar swimmingpools internet gym

Python相关问答推荐

当测试字符串100%包含查询字符串时,为什么t fuzzywuzzy s Process.extractBests不给出100%分数?

已删除的构造函数调用另一个构造函数

过载功能是否包含Support Int而不是Support Int?

symy.分段使用numpy数组

实现的差异取决于计算出的表达是直接返回还是首先存储在变量中然后返回

使文本输入中的文本与标签中的文本相同

Python中是否有方法从公共域检索搜索结果

在Pandas框架中截短至固定数量的列

如何根据条件在多指标框架上进行groupby

GL pygame无法让缓冲区与vertextPointer和colorPointer一起可靠地工作

如何让 turtle 通过点击和拖动来绘制?

Python 3.12中的通用[T]类方法隐式类型检索

替换字符串中的多个重叠子字符串

如何避免Chained when/then分配中的Mypy不兼容类型警告?

用合并列替换现有列并重命名

Scrapy和Great Expectations(great_expectations)—不合作

如何在达到end_time时自动将状态字段从1更改为0

在Python中计算连续天数

Polars将相同的自定义函数应用于组中的多个列,

Gunicorn无法启动Flask应用,因为无法将应用解析为属性名或函数调用.'"'' "