I have a dictionary that has Pandas dataframes as values. I want to get a new one DataFrame
by joining all the dataframes contained in the dictionary. The problem is that I need to create a new column where each row has the key value of that DataFrame
in the dictionary.
I think it will be better understood with an example:
We have the following dictionary, which we will call diccionario
:
{0: count eclipse_id
7 19 10453
56 12 11305
48 11 11305
1: count eclipse_id
13 9 11305
9 5 11339}
The goal is to transform it into:
count item_id user_id
19 10453 0
12 11305 0
11 11305 0
9 11305 1
5 11339 1
As can be seen, the value of each row of the column user_id
corresponds to the key that its respective DataFrame had in the original dictionary.
The simplest thing is to take advantage of
pandas.concat
and use its parameterkeys
to create the new column. The parameterkeys
is passed an iterable with an item for each dataframe to be concatenated and this item is used to create a new index. You just have to pass that index to a normal column and rename it to "user_id":Departure:
You can change the order of the columns, sort it however you want, or change the index.