Answers for "create new column pandas based on other columns"

3

change column value based on another column pandas

# Changes the 'is_electric' column based on value in the 'type' column
# If the 'type' column == 'electric' then the 'is_electric' becomes 'YES'
df['is_electric']= df['type'].apply(lambda x: 'YES' if (x == 'electric') else 'NO')
Posted by: Guest on November-19-2020
1

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')
Posted by: Guest on August-15-2021
3

pandas create new column conditional on other columns

# For creating new column with multiple conditions
conditions = [
    (df['Base Column 1'] == 'A') & (df['Base Column 2'] == 'B'),
    (df['Base Column 3'] == 'C')]
choices = ['Conditional Value 1', 'Conditional Value 2']
df['New Column'] = np.select(conditions, choices, default='Conditional Value 1')
Posted by: Guest on May-14-2020
1

Add new column based on condition on some other column in pandas.

# np.where(condition, value if condition is true, value if condition is false)

df['hasimage'] = np.where(df['photos']!= '[]', True, False)
df.head()
Posted by: Guest on August-08-2021
1

create new dataframe with columns from another dataframe pandas

new = old[['A', 'C', 'D']].copy()
Posted by: Guest on March-24-2021
0

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)
Posted by: Guest on January-07-2021

Code answers related to "create new column pandas based on other columns"

Python Answers by Framework

Browse Popular Code Answers by Language