[英]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从字典创建 Pandas 中的 DataFrame 时,会自动展开一个元组,即
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
:尝试添加
[]
,因此具有键c
的dictionary
中的值是tuple
list
:
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:传递参数
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
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:要处理第一个 dict 条目是元组的情况,您需要将所有 dict 值包含在一个列表中,以便它是可迭代的:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.