Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

pandas create column from another column

# Creates a new column 'blue_yn' based on the existing 'color' column
# If the 'color' column value is 'blue' then the new column value is 'YES'
df['blue_yn'] = np.where(df['color'] == 'blue', 'YES', 'NO')
# Can also do this using .apply and a lambda function
df['blue_yn']= df['color'].apply(lambda x: 'YES' if (x == 'blue') else 'NO') 
Comment

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)
Comment

PREVIOUS NEXT
Code Example
Python ::  
:: split column values 
:: python server 
::  
Python :: long in python 
Python :: django rest framework serializers 
Python :: python plot speichern 
Python :: how to remove last 2 rows in a dataframe 
Python :: how to find missing item in a list 
Python :: Solve linear equation with np.linalg.solve 
Python :: anaconda python 3.6 download 
Python :: No installed app with label 
Python :: tkinker 
Python :: append to list in dict python 
Python :: how to change the size of datapoint in plot python 
Python :: python flatten one liner 
Python :: Python Print hour, minute, second and microsecond 
Python :: python remove item from list 
Python :: fetch json array from mysql django 
:: python count one to ten 
::  
::  
Python :: snakeviz python profile 
Python :: python post request binary file 
Python :: sum the contents of a list python 
Python :: #Check if list1 contains all elements of list2 using all() 
Python :: You will be provided a file path for input I, a file path for output O, a string S, and a string T. 
Python :: pandas array of dataframes 
Python :: message to dict protobuf 
Python :: python time.sleep 
ADD CONTENT
Topic
Content
Source link
Name
2+6 =