python - 为什么 pandas.DataFrame.from_dict 不支持 pandas.DataFrame.to_dict 的所有方向?

标签 python pandas dataframe

为什么 DataFrame.from_dict只支持两个orient?

As per document
DataFrame.to_dict is supporting orient: str {‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’}
but DataFrame.from_dict support only two orient orient{‘columns’, ‘index’}, default columns (here columns similar to list of to_dict)

不应该是双向的吗? (比如 from_dictto_dictto_dictfrom_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

对于除indexsplit 之外的所有方向,这些都已在构造函数本身中处理。用最后两个重新创建也不难:

>>> 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_recordsfrom_dict 的附加方法,有很多方法可以解释这些输入以重建 DataFrame。在任何情况下,是否存在在 from_dictto_dict 之间交替传递数据的有效用例,足以实现其他方向?

我的直觉是否定的。

关于python - 为什么 pandas.DataFrame.from_dict 不支持 pandas.DataFrame.to_dict 的所有方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61766606/

相关文章:

r - 预处理 : text analysis on many columns from a dataframe

python - Python 中每个用户的排名

python - 按列表大小而不是 A-Z 对 Pandas 数据框进行排序

Python Polars 滚动计数

python - FastAPI 给出 ​​ "value is not a valid dict (type=type_error.dict)"

python - 我们如何将新数据写入现有的 Excel 电子表格?

python - 如何根据某些列值创建新的数据框?

python - 处理没有四舍五入、两位小数和千位分隔符的货币的通用方法

python - Kivy 自定义按钮文本

Python:在列表中查找异常值