[英]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. 每当列表中的单词在y
列中时,我都希望将其替换为同一行的x
列中的单词。 If the word isn't in y
, it should remain as is. 如果单词不在y
,则应保持原样。 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. 您可以将此转换表转换为df
,然后转换为dict
,然后将其用作所需的替换函数。
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: 如果您在pandas数据框中有转换表,则可以使用以下脚本:
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 这将覆盖您的原始列表内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.