用数据框替换列表中的单词
Replace words from list with a dataframe
我有一个单词列表。说:
list = ['this', 'that', 'and', 'more']
我想用这种方式替换单词:
x |y
-----------
this |that
plus |more
每当列表中的一个单词出现在第 y
列中时,我想将其替换为同一行第 x
列中的单词。如果单词不在 y
中,它应该保持原样。如何做到这一点?
您可以将此翻译table转换为df
,然后将其转换为dict
,然后下面将作为所需的替换功能。
d = dict(df['y', 'x'].iterrows())
new_list = [d.get(word, word) for word in list]
# new_list: ['this', 'this', 'and', 'plus']
如果您在 pandas 数据框中有翻译 table,您可以使用以下脚本:
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
这将覆盖您原来的列表内容
我有一个单词列表。说:
list = ['this', 'that', 'and', 'more']
我想用这种方式替换单词:
x |y
-----------
this |that
plus |more
每当列表中的一个单词出现在第 y
列中时,我想将其替换为同一行第 x
列中的单词。如果单词不在 y
中,它应该保持原样。如何做到这一点?
您可以将此翻译table转换为df
,然后将其转换为dict
,然后下面将作为所需的替换功能。
d = dict(df['y', 'x'].iterrows())
new_list = [d.get(word, word) for word in list]
# new_list: ['this', 'this', 'and', 'plus']
如果您在 pandas 数据框中有翻译 table,您可以使用以下脚本:
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
这将覆盖您原来的列表内容