Python/pandas:dict系列的数据框架:优化

2024-09-20 00:15:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用同一帧的数据来转换熊猫。在

我发现的唯一方法是通过这个系列的to_dict方法,这不是非常有效,因为它返回到纯python模式,而不是numpy/pandas/cython。在

你对更好的方法有什么建议吗?在

非常感谢。在

>>> import pandas as pd
>>> flagInfoSeries = pd.Series(({'a': 1, 'b': 2}, {'a': 10, 'b': 20}))
>>> flagInfoSeries
0      {'a': 1, 'b': 2}
1    {'a': 10, 'b': 20}
dtype: object
>>> pd.DataFrame(flagInfoSeries.to_dict()).T
    a   b
0   1   2
1  10  20

Tags: to数据方法importnumpypandasas模式
2条回答

我想你可以理解:

import pandas as pd

flagInfoSeries = pd.Series(({'a': 1, 'b': 2}, {'a': 10, 'b': 20}))
print flagInfoSeries
0      {u'a': 1, u'b': 2}
1    {u'a': 10, u'b': 20}
dtype: object

print pd.DataFrame(flagInfoSeries.to_dict()).T
    a   b
0   1   2
1  10  20

print pd.DataFrame([x for x in flagInfoSeries])
    a   b
0   1   2
1  10  20

计时

^{pr2}$

编辑:

如果需要保留索引,请尝试将index=flagInfoSeries.index添加到DataFrame构造函数:

print pd.DataFrame([x for x in flagInfoSeries], index=flagInfoSeries.index)

计时

In [257]: %timeit pd.DataFrame([x for x in flagInfoSeries], index=flagInfoSeries.index)
1000 loops, best of 3: 350 µs per loop

样本

import pandas as pd

flagInfoSeries = pd.Series(({'a': 1, 'b': 2}, {'a': 10, 'b': 20}))
flagInfoSeries.index = [2,8]
print flagInfoSeries
2      {u'a': 1, u'b': 2}
8    {u'a': 10, u'b': 20}

print pd.DataFrame(flagInfoSeries.to_dict()).T
    a   b
2   1   2
8  10  20

print pd.DataFrame([x for x in flagInfoSeries], index=flagInfoSeries.index)
    a   b
2   1   2
8  10  20

这样可以避免to_dict,但是{}也可能很慢:

flagInfoSeries.apply(lambda dict: pd.Series(dict))

编辑:我看到jezrael添加了计时比较。这是我的:

^{pr2}$

相关问题 更多 >