如何只替换子字符串而不替换整个字符串?

时间:2018-09-07 17:38:04

标签: python string pandas dictionary dataframe

我有一本这样的字典:

global_dict_names=dict{'com':'owb_com','cur':'cur_con','cty':'gds_cty','cur':'gds_cur'}

我的数据框如下:

com12  cur34  cty56  cur78
  a     b      c      d
  b     c      d      e

我希望我的数据框看起来像这样:

 owb_com12   cur_con34    gds_cty56    gds_cur78
  a             b            c          d
  b             c            d          e

我当前的代码如下:

GDS2018_labels.columns = [global_dict_names.get(x[:3], x) for x in 
GDS2018_labels.columns]

此当前代码将列名的前三个字符与字典中的键进行匹配。此代码的问题是它替换了整个列名,但是我只想替换与键匹配的列名的子字符串。我该如何纠正?

2 个答案:

答案 0 :(得分:3)

鉴于您的输入和期望的输出,dict是错误的数据结构选择。字典键是唯一的,这是不可协商的。

您可以使用元组列表和列表理解:

L = [('com', 'owb_com'), ('cur', 'cur_con'), ('cty', 'gds_cty'), ('cur', 'gds_cur')]

df.columns = [name.replace(old, new) for name, (old, new) in zip(df.columns, L)]

print(df)

  owb_com12 cur_con34 gds_cty56 gds_cur78
0         a         b         c         d
1         b         c         d         e

答案 1 :(得分:0)

正如jpp用户所提到的,您不应使用字典,因为您有两个相等的键。发布答案后,我才注意到这一点。检查他的答案,如果您将字典更改为仅具有相等的键,则只需使用+即可将字符串连接起来。将前缀global_dict_names.get(x[:3], x[:3])添加到后缀x[3:]

GDS2018_labels.columns = [global_dict_names.get(x[:3], x[:3]) + x[3:] for x in 
    GDS2018_labels.columns]