Change The Value Of A Particular Key Each Dictionary In A List - Python
I have a list of dictionary as shown below. [{'type': 'df_first', 'from': '2020-02-01T20:00:00.000Z', 'to': '2020-02-03T20:00:00.000Z', 'days':0, 'coef':[0.
Solution 1:
Create a new dataframe from records
(list of dictionaries), then use Series.shift
on from
column + Series.fillna
with to
column and assign it back to to
column, next use DataFrame.to_dict
to get list of dictionaries:
df = pd.DataFrame(records)
df['to'] = df['from'].shift(-1).fillna(df['to'])
records = df.to_dict('r')
Result:
# 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]}]
Post a Comment for "Change The Value Of A Particular Key Each Dictionary In A List - Python"