gpt4 book ai didi

python - 选择基于 where 语句的行

转载 作者:太空宇宙 更新时间:2023-11-03 13:06:56 25 4
gpt4 key购买 nike

我如何选择其中包含单词“链接”的值并将它们置于类别 1 中,将“爆米花”置于类别 2 中并将所有其他值置于类别 3 中?

这是一个示例,但我的实际数据集有数百行

data = {'model': [['Lisa', 'link'], ['Lisa 2', 'popcorn'], ['telephone', 'rabbit']],
'launched': [1983, 1984, 1991]}

df = pd.DataFrame(data, columns = ['model', 'launched'])

想要的

 Model                 launched         category
['Lisa', 'link'] 1983 1
['Lisa 2', 'popcorn'] 1984 2
['telephone', 'rabbit'] 1991 3

最佳答案

你可以使用 np.selectcategory 设置为 12 取决于是 'link' 还是 'popcorn' 包含在给定的列表中。对于两者都不包含的情况,将 default 设置为 3:

import numpy as np
c1 = ['link' in i for i in df.model]
c2 = ['popcorn' in i for i in df.model]
df['category'] = np.select([c1,c2], [1,2], 3)

model launched category
0 [Lisa, link] 1983 1
1 [Lisa 2, popcorn] 1984 2
2 [telephone, rabbit] 1991 3

关于python - 选择基于 where 语句的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55711325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com