[英]Setting column equal to value depending on another column pandas
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. 我坚持如何将每行中溶剂列的值设置为数据框中num列中的数字。 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.
例如,当溶剂是壬烷时,我需要num等于9,当溶剂是辛烷等时,我需要等于8,任何帮助都会很好。
use .loc
with a boolean mask 使用
.loc
和布尔掩码
df.loc[df['solvent'] == 'NONANE', 'num'] = 9
df.loc[df['solvent'] == 'OCTANE', 'num'] = 8
Another method is do define a dict and call map
: 另一种方法是定义一个dict和调用
map
:
d = {'NONANE':9, 'OCTANE':8, 'HEPTANE':7, 'HEXANE':6}
df['num'] = df['solvent'].map(d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.