Skip to content Skip to sidebar Skip to footer

Changing Pandas Dataframe Values Based On Dictionary

Is there any way to replace value using dictionary or mapping? I have dataframe like this: Q14r63: Audi Q14r2: BMW Q14r1: VW Selected

Solution 1:

Here's one approach using np.where:

import numpy as np
df[:] = np.where(df.eq('Selected'), df.columns.str.split(': ').str[1], np.nan)

print(df)

 Q14r63: Audi Q14r2: BMW Q14r1: VW
0        Audi       NaN      NaN
1         NaN       BMW       VW
2        Audi       BMW      NaN

Solution 2:

First extract by column df1['Brand'] columns with regex and then set values by mask with DataFrame.mask and missing values by DataFrame.where:

v = df.columns.str.extract('(' + '|'.join(df1['Brand']) + ')', expand=False)
print (v)
Index(['Audi', 'BMW', 'VW'], dtype='object')

m = df.eq('Selected')
print (m)
   Q14r63: Audi  Q14r2: BMW  Q14r1: VW
0TrueFalseFalse1FalseTrueTrue2TrueTrueFalse

df = df.mask(m, v[None, :]).where(m)
print (df)
  Q14r63: Audi Q14r2: BMW Q14r1: VW
0         Audi        NaN       NaN
1          NaN        BMW        VW
2         Audi        BMW       NaN

Alternative solution with numpy.where and DataFrame constructor:

df = pd.DataFrame(np.where(m, v, np.nan), index=df.index, columns=df.columns)
print (df)
  Q14r63: Audi Q14r2: BMW Q14r1: VW
0         Audi        NaNNaN1NaN        BMW        VW
2         Audi        BMW       NaN

Solution 3:

Try

brand_map = dict(zip(df2.Code, df2.Brand))
{63: 'Audi', 2: 'BMW', 1: 'VW'}

mapped_values = df.columns.str.extract('Q14r(\d+)')[0].astype(int).map(brand_map)
df[:] = np.where(df == 'Selected', mapped_values, np.nan)

  Q14r63: Audi Q14r2: BMW Q14r1: VW
0         Audi        NaN       NaN
1          NaN        BMW        VW
2         Audi        BMW       NaN

Solution 4:

df1 =

Q14r63: Audi                 Q14r2: BMW                 Q14r1: VW 

Selected                     Not Selected               Not Selected
Not Selected                 Selected                   Selected 
Selected                     Selected                   Not Selected 

df2 =

Brand           Code
Audi             63
BMW              2
VW               1

You can do something like this,

forcolumnin df1.columns: 
    brand = [x forxin df2['Brand'].values if x in column][0]
    df1[column] = df1[column].replace({'Selected': brand, 'Not Selected': 'NaN'})

Post a Comment for "Changing Pandas Dataframe Values Based On Dictionary"