Skip to content Skip to sidebar Skip to footer

Sort The List Of Dictionaries Based On Date Column Of Dataframe In Pandas

I have a input list and dataframe as shown below. [{'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,

Solution 1:

Define a function add_dct that takes arguments as list of dictionaries lst with _type, _from and _to and appends a new dictionary to lst:

dmin, dmax = df['Date'].min(), df['Date'].max()
defadd_dct(lst, _type, _from, _to):
    lst.append({
        'type': _type,
        'from': _fromifisinstance(_from, str) else _from.strftime("%Y-%m-%dT20:%M:%S.000Z"),
        'to': _to ifisinstance(_to, str) else _to.strftime("%Y-%m-%dT20:%M:%S.000Z"),
        'days': 0,
        "coef":[0.1,0.1,0.1,0.1,0.1,0.1]
    })

Follow this steps as according to your predefined requirements:

# STEP 1
lst = sorted(lst, key=lambda d: pd.Timestamp(d['from']))

# STEP 2
add_dct(lst, 'df_first', dmin, lst[0]['from'])

# STEP 3
add_dct(lst, 'df_mid', dmin + pd.Timedelta(days=7), dmin + pd.Timedelta(days=8))

# STEP 4
add_dct(lst, 'df_last', dmax, dmax)

# STEP 5
lst = sorted(lst, key=lambda d: pd.Timestamp(d['from']))

Result:

[{'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-05T20: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': 'df_mid',
  'from': '2020-02-08T20:00:00.000Z',
  'to': '2020-02-09T20:00:00.000Z',
  'days': 0,
  'coef': [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]},
 {'type': 'df_last',
  'from': '2020-03-14T20:00:00.000Z',
  'to': '2020-03-14T20:00:00.000Z',
  'days': 0,
  'coef': [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]}]

Post a Comment for "Sort The List Of Dictionaries Based On Date Column Of Dataframe In Pandas"