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

查看:342
本文介绍了根据另一列 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天全站免登陆