简体   繁体   中英

Prevent Pandas from unpacking a tuple when creating a dataframe from dict

When creating a DataFrame in Pandas from a dictionary, a tuple is automatically expanded, ie

import pandas
d = {'a': 1, 'b': 2, 'c': (3,4)}
df = pandas.DataFrame.from_dict(d)
print(df)

returns

   a  b  c
0  1  2  3
1  1  2  4

Apart from converting the tuple to string first, is there any way to prevent this from happening? I would want the result to be

   a  b  c
0  1  2  (3, 4)

Try add [] , so value in dictionary with key c is list of tuple :

import pandas

d = {'a': 1, 'b': 2, 'c': [(3,4)]}
df = pandas.DataFrame.from_dict(d)

print(df)
   a  b       c
0  1  2  (3, 4)

Pass param orient='index' and transpose the result so it doesn't broadcast the scalar values:

In [13]:
d = {'a': 1, 'b': 2, 'c': (3,4)}
df = pd.DataFrame.from_dict(d, orient='index').T
df

Out[13]:
   a       c  b
0  1  (3, 4)  2

To handle the situation where the first dict entry is a tuple, you'd need to enclose all the dict values into a list so it's iterable:

In [20]:
d = {'a': (5,6), 'b': 2, 'c': 1}
d1 = dict(zip(d.keys(), [[x] for x in d.values()]))
pd.DataFrame.from_dict(d1, orient='index').T

Out[23]:
        a  b  c
0  (5, 6)  2  1

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