为什么 DataFrame.from_dict
只支持两个orient?
As per document
DataFrame.to_dict
is supportingorient: str {‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’}
butDataFrame.from_dict
support only two orientorient{‘columns’, ‘index’}, default columns
(herecolumns
similar tolist
ofto_dict
)
不应该是双向的吗? (比如 from_dict
到 to_dict
和 to_dict
到 from_dict
)
最佳答案
实际原因可能是因为,没有必要:
df = pd.DataFrame({c: list(c) for c in 'ABC DEF'.split()})
# df
# ABC DEF
# 0 A D
# 1 B E
# 2 C F
orients = ['dict', 'list', 'series', 'records', 'index', 'split']
for o in orients:
print(f'With orient {o}:')
print(pd.DataFrame(df.to_dict(o)), '\n')
观察仅使用默认的 DataFrame
构造函数会发生什么:
With orient dict:
ABC DEF
0 A D
1 B E
2 C F
With orient list:
ABC DEF
0 A D
1 B E
2 C F
With orient series:
ABC DEF
0 A D
1 B E
2 C F
With orient records:
ABC DEF
0 A D
1 B E
2 C F
With orient index:
0 1 2
ABC A B C
DEF D E F
With orient split:
Traceback (most recent call last):
...
ValueError: arrays must all be same length
对于除index
和split
之外的所有方向,这些都已在构造函数本身中处理。用最后两个重新创建也不难:
>>> pd.DataFrame(df.to_dict('index')).T
ABC DEF
0 A D
1 B E
2 C F
>>> pd.DataFrame(**df.to_dict('split'))
ABC DEF
0 A D
1 B E
2 C F
有了 from_records
和 from_dict
的附加方法,有很多方法可以解释这些输入以重建 DataFrame
。在任何情况下,是否存在在 from_dict
和 to_dict
之间交替传递数据的有效用例,足以实现其他方向?
我的直觉是否定的。
关于python - 为什么 pandas.DataFrame.from_dict 不支持 pandas.DataFrame.to_dict 的所有方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61766606/