查找并删除 pandas 数据帧每行中字符串中最长的字符串

问题描述 投票:0回答:1

我有一个 csv 文件,正在将其导入 pandas 数据框。以下是其中一列中的数据示例。分隔符之间的每个值都是我要使用的“标签”。我也有不想用作标签的值...这些值是“长”值,本质上是某种产品描述,而不是标签。

Anthropologie Dolan Women's S Green Long Sleeves Tie Front Dress\,Girl\, Woman\, USA\, American\, Chic
Button\,Logo\,Blue Skinny Crop Denim Raw Hem Ankle Denim Jeans

我首先完成替换以获得我需要的正确分隔符(我从配置文件中获取需要应用此的列列表):

for col in config["wooAttributeReplace"]:
    woo_product_list[col] = woo_product_list[col].replace(r'\\,', '|', regex=True)

并得到这个:

Anthropologie Dolan Women's S Green Long Sleeves Tie Front Dress|Girl| Woman| USA| American| Chic
Button|Logo|Blue Skinny Crop Denim Raw Hem Ankle Denim Jeans

我的最终输出将如下所示:

Girl | Woman | USA | American | Chic
Button | Logo

我原本以为“长”的产品描述部分总是放在第一位,所以我尝试了这个:

woo_product_list[col].mask(woo_product_list[col].str.len() > 40, woo_product_list[col].str.split('|', n=1).str.get(-1), inplace=True)
which led to this:
Girl| Woman| USA| American| Chic
Logo|Blue Skinny Crop Denim Raw Hem Ankle Denim Jeans

但这对于多种场景来说并不是真正正确的解决方案(即产品字符串不是第一个),我想我现在要做的是“找到字符串中最长的字符串(在 | 分隔符之间)并将其删除.希望这有足够的意义,如果有人有任何提示,我将不胜感激。谢谢!

python pandas data-manipulation
1个回答
0
投票

如果我理解正确的话,你想用

,
分割字符串,然后从列表中删除最长的字符串。

假设你有这个数据框:

                                                                                             Column1
0  Anthropologie Dolan Women's S Green Long Sleeves Tie Front Dress,Girl, Woman, USA, American, Chic
1                                       Button,Logo,Blue Skinny Crop Denim Raw Hem Ankle Denim Jeans

然后

# make attributes column
df["Attributes"] = df["Column1"].apply(lambda x: list(map(str.strip, x.split(","))))

# remove longest string
df["Attributes"] = df["Attributes"].apply(
    lambda x: [v for m in [max(x, key=len)] for v in x if v != m]
)

print(df)

打印:

                                                                                             Column1                          Attributes
0  Anthropologie Dolan Women's S Green Long Sleeves Tie Front Dress,Girl, Woman, USA, American, Chic  [Girl, Woman, USA, American, Chic]
1                                       Button,Logo,Blue Skinny Crop Denim Raw Hem Ankle Denim Jeans                      [Button, Logo]
© www.soinside.com 2019 - 2024. All rights reserved.