gpt4 book ai didi

python - 数据帧 : change value in column when value in another column is in dict

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:28 24 4
gpt4 key购买 nike

首先是我的数据框的外观:

temp = df{'assigned to':('user1','user2','user3'),'model':('ipad air 2','galaxy a5', 'ipad air'), 'type':''}

'assigned to' 'model' 'type'
user1 ipad air 2
user2 galaxy a5
user3 ipad air

上面的输入是给定数据的片段,我只添加了列类型。我还使用字典:

dictMobile{'galaxy a5':'samsung galaxy a5','galaxy a6':'samsung galaxy a7'}

使用这本字典,我替换了 temp['model'] 中的值,以便命名保持一致。现在,如果模型显示在 dictMobile 中,我还想在列中添加“mobile”类型,如果没有显示,则添加“tablet”类型。

到目前为止我想到的最好的是

if temp['model'] in dictMobile:
temp['Type'] = 'mobile'
else:
temp['Type'] = 'tablet'

但这给我带来了错误“TypeError:'Series'对象是可变的,因此它们不能被散列”。

我想要的结果是:

'assigned to' 'model'    'type'
user1 ipad air 2 tablet
user2 galaxy a5 mobile
user3 ipad air tablet

最佳答案

使用numpy.where条件为 isin用于检查 dictkeys:

df['type'] = np.where(df['model'].isin(dictMobile.keys()), 'mobile','tablet')
print (df)
assigned to model type
0 user1 ipad air 2 tablet
1 user2 galaxy a5 mobile
2 user3 ipad air tablet

关于python - 数据帧 : change value in column when value in another column is in dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46730795/

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