更改列表中每个字典的特定键的值 - python

Posted

技术标签:

【中文标题】更改列表中每个字典的特定键的值 - python【英文标题】:Change the value of a particular key each dictionary in a list - python 【发布时间】:2020-11-07 08:07:18 【问题描述】:

我有一个字典列表,如下所示。

["type": "df_first",
      "from": "2020-02-01T20:00:00.000Z",
      "to": "2020-02-03T20:00:00.000Z",
      "days":0,
      "coef":[0.1,0.1,0.1,0.1,0.1,0.1]
      ,
 "type": "quadratic",
  "from": "2020-02-03T20:00:00.000Z",
  "to": "2020-02-10T20:00:00.000Z",
  "days":3,
  "coef":[0.1,0.1,0.1,0.1,0.1,0.1]
      ,
"type": "linear",
      "from": "2020-02-04T20:00:00.000Z",
      "to": "2020-02-03T20:00:00.000Z",
      "days":3,
      "coef":[0.1,0.1,0.1,0.1,0.1,0.1]
      ,
"type": "polynomial",
 "from": "2020-02-08T20:00:00.000Z",
 "to": "2020-02-08T20:00:00.000Z",
 "days":3,
 "coef":[0.1,0.1,0.1,0.1,0.1,0.1]
      
]

从上面的字典中,我想将每个字典的“to”值替换为下一个字典的“from”值。

最后一个字典的“to”值保持原样

预期输出:

["type": "df_first",
          "from": "2020-02-01T20:00:00.000Z",
          "to": "2020-02-03T20:00:00.000Z",
          "days":0,
          "coef":[0.1,0.1,0.1,0.1,0.1,0.1]
          ,
     "type": "quadratic",
      "from": "2020-02-03T20:00:00.000Z",
      "to": "2020-02-04T20:00:00.000Z",
      "days":3,
      "coef":[0.1,0.1,0.1,0.1,0.1,0.1]
          ,
    "type": "linear",
          "from": "2020-02-04T20:00:00.000Z",
          "to": "2020-02-08T20:00:00.000Z",
          "days":3,
          "coef":[0.1,0.1,0.1,0.1,0.1,0.1]
          ,
    "type": "polynomial",
     "from": "2020-02-08T20:00:00.000Z",
     "to": "2020-02-08T20:00:00.000Z",
     "days":3,
     "coef":[0.1,0.1,0.1,0.1,0.1,0.1]
          ]

【问题讨论】:

【参考方案1】:

records(字典列表)创建一个新数据框,然后在from 列上使用Series.shift + Series.fillnatocolumn 并将其分配回to 列,接下来使用@987654323 @ 获取字典列表:

df = pd.DataFrame(records)
df['to'] = df['from'].shift(-1).fillna(df['to'])
records = df.to_dict('r')

结果:

# print(records)

['type': 'df_first',
  'from': '2020-02-01T20:00:00.000Z',
  'to': '2020-02-03T20:00:00.000Z',
  'days': 0,
  'coef': [0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
 'type': 'quadratic',
  'from': '2020-02-03T20:00:00.000Z',
  'to': '2020-02-04T20:00:00.000Z',
  'days': 3,
  'coef': [0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
 'type': 'linear',
  'from': '2020-02-04T20:00:00.000Z',
  'to': '2020-02-08T20:00:00.000Z',
  'days': 3,
  'coef': [0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
 'type': 'polynomial',
  'from': '2020-02-08T20:00:00.000Z',
  'to': '2020-02-08T20:00:00.000Z',
  'days': 3,
  'coef': [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]]

【讨论】:

创建了一个新问题,请在空闲时间查看该问题***.com/questions/62959037/…

以上是关于更改列表中每个字典的特定键的值 - python的主要内容,如果未能解决你的问题,请参考以下文章

如何在Python中更改嵌套字典中键的值[关闭]

如何展平Python字典中键的值(元组列表列表)?

Python 字典方法

Python 字典方法

如何将带有字典列表的熊猫列拆分为每个键的单独列

python 一个由字典构成的列表,修改其中1个字典的键的值,却把该列表所有字典相同的键的值都一起修改了?