【问题标题】:Change the value of a particular key each dictionary in a list - python更改列表中每个字典的特定键的值 - 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]
          }]

【问题讨论】:

    标签: python-3.x pandas list dataframe dictionary


    【解决方案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]}]
    

    【讨论】:

    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 2022-11-24
    • 2021-02-08
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-05
    相关资源
    最近更新 更多