简体   繁体   中英

Replace Pandas DataFrame column values based on containing dictionary keys

Here is an example, where column is assigned when the row is<\/strong> a dictionary key: https:\/\/stackoverflow.com\/a\/20250996\/12603542<\/a>

import pandas as pd
df = pd.DataFrame({'col1': {0: 'aba', 1: 'abc', 2: 'abx'}})

#gives me a DataFrame
     col1 
0    aba #contains 'ba'
1    abc #will NOT be replaced
2    abx #contains 'bx'

dictionary = {'ba': 5, 'bx': 8}

#and I need to get:

     col1 
0    5
1    abc
2    8

You could use DataFrame.replace<\/code><\/a> with regex<\/code> parameter set to True and pass the mapping dictionary.

df.replace(dictionary, regex=True)

#   col2
# 0    5
# 1  abc
# 2    8

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