我有一个巨大的 Dataframe,其中有很多条目需要更改。因此,我创建了一个翻译字典,其结构如下:
{'Data.Bar Layer': {'1': 0,
'1.E': 21,
'2': 13,
'2.E': 22,
'3': 14,
'3.E': 24,
'4': 15,
'4.E': 23,
'B': 16,
'CL1': 1,
'CL2': 2,
'CL2a': 6,
'CL3': 3,
'CL3a': 4,
'CL4': 5,
'E': 18,
'L1': 7,
'L2': 8,
'L2a': 12,
'L3': 9,
'L3a': 10,
'L4': 11,
'T': 17,
'T&B': 19,
'T+B': 20},
'Data.Bar Type': {'N': 0, 'R': 1},
'Data.Defined No. Bars': {'No': 0, 'Yes': 1},
'Data.Design Option': {'-1': 0, 'Main Model': 1},...}
screenshot of the dictionaries print representation
第一个键对应于数据框列,第二个键对应于需要更改的值,例如在 Data.Bar Layer
列中,所有 '1'
都应为 0。This is how the documentation of pandas.dataframe.replace states the dictionary to look like
但是,必须多次交换相同的值,这(我猜)会导致错误:
Replacement not allowed with overlapping keys and values
Here is a snippet of the Dataframe.是否有任何解决方法可以避免此错误?我尝试了一些使用 apply 和 map 的方法,但不幸的是它们没有用。
在此先感谢您和亲切的问候, 最大
最佳答案
可能有更 pythonic 的方式,但这段代码对我有用;
for col in your_dict.keys():
df[col].replace(your_dict[col], inplace=True)
关于python - DataFrame.替换为嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55271574/