python - DataFrame.替换为嵌套字典

标签 python pandas dataframe

我有一个巨大的 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/

相关文章:

apache-spark - Spark : Match columns from two dataframes

python - 使用网站中的数据,将其与表格匹配并提取数据

Python子进程: How to run a python script using a different intepreter than the main thread

python - 如何在 Python 中逐字符读取 UTF 文件

python - 无法使用 selenium、python 和 chromedriver 与页面中的元素交互

python - 根据不同列的值从 Pandas 列表列中获取列表元素

python - 绘制包含 HH :MM format in a single figure matplotlib 的数据帧

python - 返回 groupby pandas 之后的所有行(即不是减少的行数,这是组键的唯一值)

python - 从一个 Dataframe 到另一个 Dataframe 查找元素并返回其索引的快速方法

python - Pandas ,基于列值的条件列分配