简体   繁体   中英

Replace words from list with a dataframe

I have a list of words. Say:

list = ['this', 'that', 'and', 'more']

I want to replace words in such fashion:

x    |y
-----------
this |that
plus |more

Every time a word from the list is in column y , I want to replace it with what's found in column x on the same row. If the word isn't in y , it should remain as is. How can this be done?

You can convert this translation table, call it df , to a dict , then the following will act as the desired replacement function.

d = dict(df['y', 'x'].iterrows())

new_list = [d.get(word, word) for word in list]

# new_list: ['this', 'this', 'and', 'plus']

If you have the translation table in pandas dataframe you can use the following script:

import pandas as pd
list1 = ['this', 'that', 'and', 'more']
df = pd.DataFrame(dict(zip(['x', 'y'], [['this', 'plus'], ['that', 'more']])))

for i,item in enumerate(list1):
    if item in df.y.values:
        repvalue = df.x[df.y == item].values[0]
        list1[i] = repvalue

This will overwrite your original list content

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