繁体   English   中英

用数据框替换列表中的单词

[英]Replace words from list with a dataframe

我有一个词表。 说:

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

我想以这种方式替换单词:

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

每当列表中的单词在y列中时,我都希望将其替换为同一行的x列中的单词。 如果单词不在y ,则应保持原样。 如何才能做到这一点?

您可以将此转换表转换为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数据框中有转换表,则可以使用以下脚本:

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

这将覆盖您的原始列表内容

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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