更改列表中每个字典的特定键的值 - 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.fillna
和to
column 并将其分配回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的主要内容,如果未能解决你的问题,请参考以下文章