简体   繁体   中英

Pandas create dataframe from dict converting tuple to index

Is there a convenient way to implement a function make_dataframe , used as follows

mydict = {
    ('tom', 'gray') : [1,2,3,4,5],
    ('bill', 'ginger') : [6,7,8,9,10],
}

make_dataframe(mydict, tupleLabels=['catname', 'catcolor'], valueLabel='weight')

Expected result

| catname | catcolor | weight |
| tom | gray | 1 |
| tom | gray | 2 |
| tom | gray | 3 |
| tom | gray | 4 |
| tom | gray | 5 |
| bill | ginger | 6 |
| bill | ginger | 7 |
| bill | ginger | 8 |
| bill | ginger | 9 |
| bill | ginger | 10 |

It does not sound too difficult, I just don't want to reinvent the wheel

You can create your own function using dataframe unstack after renaming the labels using rename_axis :

def make_dataframe(dictionary , tupleLabels , valueLabel):
    return (pd.DataFrame(dictionary).rename_axis(tupleLabels,axis=1)
            .unstack().reset_index(tupleLabels,name=valueLabel))

out = make_dataframe(mydict, tupleLabels=['catname', 'catcolor'], valueLabel='weight')

print(out)

  catname catcolor  weight
0     tom     gray       1
1     tom     gray       2
2     tom     gray       3
3     tom     gray       4
4     tom     gray       5
0    bill   ginger       6
1    bill   ginger       7
2    bill   ginger       8
3    bill   ginger       9
4    bill   ginger      10

Your dictionary is misformatted for easy conversion to a Pandas DataFrame.

I suggest doing the following:


mydict = {
    ('tom', 'gray') : [1,2,3,4,5],
    ('bill', 'ginger') : [6,7,8,9,10],
}

l = [ [ k[0], k[1], val ] for k, v in mydict.items() for val in v ]

df = pd.DataFrame(l, columns=['catname', 'catcolor', 'weight'])

Which yields:

  catname catcolor  weight
0     tom     gray       1
1     tom     gray       2
2     tom     gray       3
3     tom     gray       4
4     tom     gray       5
5    bill   ginger       6
6    bill   ginger       7
7    bill   ginger       8
8    bill   ginger       9
9    bill   ginger      10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM