pandas create new column in place=true code example

Example 1: create new columns pandas from another column

def label_race (row):
   if row['eri_hispanic'] == 1 :
      return 'Hispanic'
   if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
      return 'Two Or More'
   if row['eri_nat_amer'] == 1 :
      return 'A/I AK Native'
   if row['eri_asian'] == 1:
      return 'Asian'
   if row['eri_afr_amer']  == 1:
      return 'Black/AA'
   if row['eri_hawaiian'] == 1:
      return 'Haw/Pac Isl.'
   if row['eri_white'] == 1:
      return 'White'
   return 'Other'

df.apply(lambda row: label_race(row), axis=1)

Example 2: new column in pandas with where logic

virtsizes = {
  "type1": { "gb": 1.2, "xxx": 0, "yyy": 30 },
  "type2": { "gb": 1.5, "xxx": 2, "yyy": 20  },
  "type3": { "gb": 2.3, "xxx": 0.1, "yyy": 10  },
}
d = {k:v['gb'] for k,v in virtsizes.items()}
print (d)
{'type2': 1.5, 'type1': 1.2, 'type3': 2.3}

df = pd.DataFrame({'vol-type':['type1','type2']})
df["real_size"] = df["vol-type"].map(d)
print (df)
  vol-type  real_size
0    type1        1.2
1    type2        1.5