[英]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.