从dict创建数据帧时,防止Pandas解包元组

时间:2016-05-09 10:32:45

标签: python pandas

当从字典中创建Pandas中的DataFrame时,会自动扩展元组,即

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
1  1  2  4

除了首先将元组转换为字符串之外,还有什么方法可以防止这种情况发生吗?我希望结果是

   a  b  c
0  1  2  (3, 4)

2 个答案:

答案 0 :(得分:2)

尝试添加[],因此dictionary的{​​{1}}项值为c的{​​{1}}:

list

答案 1 :(得分:1)

传递参数orient='index'并转置结果,以便它不会广播标量值:

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