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 :: merge two dictionaries in a single expression 
Python :: remove duplicates function python 
Python :: pyautogui moveTo overtime 
Python :: Handling Python DateTime timezone 
Python :: what value do we get from NULL database python 
Python :: In file included from psycopg/psycopgmodule.c:28:./psycopg/psycopg.h:35:10: fatal error: Python.h: No such file or directory35 | #include <Python.h| ^~~~~~~~~~compilation terminated. 
Python :: To View the entire Row and Column in a Dataframe 
Python :: pandas read dictionary 
Python :: python opencv draw rectangle with mouse 
Python :: hide code in jupyter notebook 
Python :: multinomial regression scikit learn 
Python :: python printing to a file 
Python :: datetime to int in pandas 
Python :: python program to convert unit 
Python :: how to do a square root in python 
Python :: python unzip list of tuples 
Python :: python console width 
Python :: change column names with number pd dataframe 
Python :: convert decimal to hex python 
Python :: skip error python 
Python :: standard scaler vs min max scaler 
Python :: numpy matrix power 
Python :: read csv and store in dictionary python 
Python :: python closure 
Python :: how to add header in csv file in python 
Python :: python read in integers separated by spaces 
Python :: python class 
Python :: change font size in plt 
Python :: how to extract integers from string python 
Python :: length of dataframe 
ADD CONTENT
Topic
Content
Source link
Name
1+2 =