Setting column equal to value depending on another column pandas

三世轮回 提交于 2019-12-08 06:03:45

问题


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.


回答1:


use .loc with a boolean mask

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

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)


来源:https://stackoverflow.com/questions/34158320/setting-column-equal-to-value-depending-on-another-column-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!