2

我有一本看起来像这样的字典:

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]

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

4

2 回答 2

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
于 2018-09-07T17:46:06.950 回答
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]
于 2018-09-07T17:43:10.173 回答