Home > Software design >  How to split a dictionary keys at "_" and create two dimensional table?
How to split a dictionary keys at "_" and create two dimensional table?

Time:09-17

I have a dictionary like this:

dict = {"a_1":20,"b_1":5,"a_2":8,"b_2":7}

I want to split the dictionary at underlines ("_") and create a table like this:

enter image description here

I try to split keys with:

[key.split('_') for key in dict.keys()]

i could not use the result in pandas. How do i create the table using pandas?

CodePudding user response:

So in your case you can do pass the dict to pd.Series , then split the index , and unstack . Notice : do not name dict as 'dict'

s = pd.Series(d)
s.index=s.index.str.split('_').map(tuple)
s = s.unstack(level=0)
s
    a  b
1  20  5
2   8  7
  • Related