根据另一列 pandas 设置列等于值 [英] Setting column equal to value depending on another column pandas

查看:34
本文介绍了根据另一列 pandas 设置列等于值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在如何将每行中溶剂列的值设置为数据框中 num 列中的数字.例如,当溶剂是壬烷时,我需要 num 等于 9,当溶剂是辛烷等时,我需要 num 等于 8.任何帮助都会很棒.

I am stuck on how to set the value of solvent column in each row to a number in the num column in the data frame. eg I need num to be equal to 9 when solvent is Nonane and num equal to 8 when solvent is Octane etc. Any help would be great.

推荐答案

使用带有布尔掩码的 .loc

df.loc[df['solvent'] == 'NONANE', 'num'] = 9
df.loc[df['solvent'] == 'OCTANE', 'num'] = 8

另一种方法是定义一个字典并调用map:

Another method is do define a dict and call map:

d = {'NONANE':9, 'OCTANE':8, 'HEPTANE':7, 'HEXANE':6}
df['num'] = df['solvent'].map(d)

这篇关于根据另一列 pandas 设置列等于值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆