用数据框中的值替换列表的元素

问题描述 投票:0回答:1

我有一个数据字典和一个column_list。我想用数据字典中的匹配值替换 column_list 中的值。我写了下面的代码;但是,我无法获得所需的输出。 有人可以帮忙修复重叠值吗?

col_list = ['eff_strt_dte', 'eff_sta_dt', 'birth_dt', 'cus_idr', 'cust_id']
data_dict = {'eff': 'effective', 'dt': 'date', 'dte': 'date', 'str': 'start', 'cus': 'customer', 'cust': 'customer', 'id':'identifier', 'idr': 'identifier', 'sta': 'start'}

new_list = []
for col in col_list:
    for key, value in data_dict.items():
        if key in col:
            col = col.replace(key, value)
    new_list.append(col)
print(new_list)

预期输出为:

['effective_start_date', 'effective_start_date', 'birth_date', 'customer_identifier', 'customer_identifier']

我现在得到的输出:

['effective_startt_datee', 'effective_sta_date', 'birth_date', 'customeromer_identifierr', 'customeromert_identifier']

python list replace
1个回答
0
投票

你就快到了!只需更换即可

        if key in col:

        if key in col.split('_'):

并将键值对

'strt': 'start'
包含在
data_dict

© www.soinside.com 2019 - 2024. All rights reserved.