问题
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