python - 根据字符串列表修改数据框行

标签 python pandas numpy

背景

我有一个数据集,其中包含以下内容:

product_title   price
Women's Pant    20.00
Men's Shirt     30.00
Women's Dress   40.00
Blue 4" Shorts  30.00
Blue Shorts     35.00
Green 2" Shorts 30.00

我创建了一个名为“性别”的新列,其中包含基于product_title 中指定字符串的“女性”、“男性”或“男女皆宜”值。

输出如下所示:

product_title   price   gender
Women's Pant    20.00   women
Men's Shirt     30.00   men
Women's Dress   40.00   women
Blue 4" Shorts  30.00   women
Blue Shorts     35.00   unisex
Green 2" Shorts 30.00   women

方法

我尝试使用 if/else 语句创建一个新列:

df['gender'] = ['women' if 'women' in word or 'Blue 4"' in word or 'Green 2"' in word
                else "men" if "men" in word
                else "unisex" 
                for word in df.product_title.str.lower()]

尽管这种方法有效,但当我有很多条件来标记女性、男性和男女皆宜时,它就会变得很长。有没有更干净的方法来做到这一点?有没有办法可以传递字符串列表,而不是使用长链或条件?

我非常感谢帮助,因为我是 python 和 pandas 库的新手。

最佳答案

IIUC,

import numpy as np
s = df['product title'].str.lower()
df['gender'] = np.select([s.str.contains('men'), 
                          s.str.contains('women|blue 4 shorts|green 2 shorts')], 
                         ['men', 'women'],
                         default='unisex')

关于python - 根据字符串列表修改数据框行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62901885/

相关文章:

python - 禁止直接赋值给多对多集合的前端。使用 emails_for_help.set() 代替

python - 我们可以在 Hadoop Streaming 中级联多个 MapReduce 作业吗(lang : Python)

python - 如何防止 lambda 函数局部变量在 python 中更改?

python - 当存在 NaN 并且您想使用 groupby 时

python - 如何计算基于多级索引的时间戳差异?

python - 用 numpy 进行矢量化基数排序——它能打败 np.sort 吗?

python - 盈透证券自动交易

python - 删除或替换列名中的空格

python - 性能:Pandas index.intersection() 与集合交集

python - 使用变量名称作为字典理解中的键