Underoos
Underoos

Reputation: 5200

How to create a dictionary of items from a dataframe?

I have a Pandas dataframe df which is of the form:

pk  id_column   date_column sales_column
0   111         03/10/19    23
1   111         04/10/19    24
2   111         05/10/19    25
3   111         06/10/19    26
4   112         07/10/19    27
5   112         08/10/19    28
6   112         09/10/19    29
7   112         10/10/19    30
8   113         11/10/19    31
9   113         12/10/19    32
10  113         13/10/19    33
11  113         14/10/19    34
12  114         15/10/19    35
13  114         16/10/19    36
14  114         17/10/19    37
15  114         18/10/19    38

How do I get a new dictionary which contains data from id_column and sales_column as its value like below in the order of date_column.

{
    111: [23, 24, 25, 26],
    112: [27, 28, 29, 30],
    113: ...,
    114: ...
}

Upvotes: 1

Views: 55

Answers (1)

jezrael
jezrael

Reputation: 863611

First create Series of lists in groupby with list and then convert to dictionary by Series.to_dict:

If need sorting by id_column and date_column first convert values to datetimes and then use DataFrame.sort_values:

df['date_column'] = pd.to_datetime(df['date_column'], dayfirst=True)
df = df.sort_values(['id_column','date_column'])

d = df.groupby('id_column')['sales_column'].apply(list).to_dict()
print (d)

{111: [23, 24, 25, 26], 112: [27, 28, 29, 30], 113: [31, 32, 33, 34], 114: [35, 36, 37, 38]}

Upvotes: 4

Related Questions