'When converting a dataframe to a dictionary, how do I extract only part of the dataframe to be the key?
Here is what the dataframe looks like. It was retrieved from Santiment.
ethSpent
datetime
2020-04-17 00:00:00+00:00 0.0
2020-04-17 01:00:00+00:00 0.0
df.todict()
Here is what one pair of key and value looks like
Timestamp('2021-04-14 20:00:00+0000', tz='UTC'): 0.0,
How do I only extract the datetime without the Timestamp and tz='UTC'?
Solution 1:[1]
You could do it like this without changing the original df.
df = pd.DataFrame({
'date' : pd.date_range('1/1/2022', '1/5/2022', freq='1D', tz='UTC'),
'value' : list(range(5))
})
df.assign(data=lambda x: x['date'].dt.date)[['data','value']].to_dict()
Output:
{'data': {0: datetime.date(2022, 1, 1),
1: datetime.date(2022, 1, 2),
2: datetime.date(2022, 1, 3),
3: datetime.date(2022, 1, 4),
4: datetime.date(2022, 1, 5)},
'value': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}}
Like in the comments asked. You can just go with .reset_index() and then assigning like before:
df.reset_index().assign(data=lambda x: x['date'].dt.date)[['data','value']].to_dict()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
