Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a new column with key information in that column from dictionary of different length array without loosing any value in pandas in python

Input

dict_table = {'Table1': [1, 2,], 'Table2': [3, 4, 5], 'Table3': [6, 7, 8, 9, 10, 11]}

Result

Table_name Table_value New_Column
Table1 1 Table1
Table1 2 Table1
Table2 3 Table2
Table2 4 Table2
Table2 5 Table2
Table3 6 Table3
Table3 7 Table3
Table3 8 Table3
Table3 9 Table3
Table3 10 Table3
Table3 11 Table3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can get the result from the dictionary using:

out = (pd.Series(dict_table).explode()
         .rename_axis('Table_name').reset_index(name='Table_value')
       )

Or:

out = pd.DataFrame([[k, v] for k, l in dict_table.items() for v in l],
                   columns=['Table_name', 'Table_value'])

Output:

   Table_name Table_value
0      Table1           1
1      Table1           2
2      Table2           3
3      Table2           4
4      Table2           5
5      Table3           6
6      Table3           7
7      Table3           8
8      Table3           9
9      Table3          10
10     Table3          11
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading