简体   繁体   中英

code multiple columns based on lists and dictionaries in Python

I have the following dataframe in Pandas

 OfferPreference_A  OfferPreference_B   OfferPreference_C   
            A          B                  A                  
            B          C                  C                 
            C          S                  G  

I have the following dictionary of unique values under all the columns

  dict1={A:1, B:2, C:3, S:4, G:5, D:6}

I also have a list of the columnames

  columnlist=['OfferPreference_A', 'OfferPreference_B', 'OfferPreference_C']

I Am trying to get the following table as the output

    OfferPreference_A   OfferPreference_B   OfferPreference_C   
               1           2                  1                  
               2           3                 3                  
               3           4                  5  

How do I do this.

Use:

#if value not match get NaN
df = df[columnlist].applymap(dict1.get)

Or:

#if value not match get original value
df = df[columnlist].replace(dict1)

Or:

#if value not match get NaN
df = df[columnlist].stack().map(dict1).unstack()

print (df)
   OfferPreference_A  OfferPreference_B  OfferPreference_C
0                  1                  2                  1
1                  2                  3                  3
2                  3                  4                  5

You can use map for this like shown below, assuming the values will match always

for col in columnlist:
    df[col] = df[col].map(dict1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM