从条目长度不同的字典创建数据框 [英] Creating dataframe from a dictionary where entries have different lengths

查看:57
本文介绍了从条目长度不同的字典创建数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一本包含10个键值对的字典.每个条目都包含一个numpy数组.但是,所有数组的长度都不相同.

Say I have a dictionary with 10 key-value pairs. Each entry holds a numpy array. However, the length of the array is not the same for all of them.

如何创建每列包含不同条目的数据框?

How can I create a dataframe where each column holds a different entry?

当我尝试时:

pd.DataFrame(my_dict)

我得到:

ValueError: arrays must all be the same length

有什么办法可以克服这个问题?我很高兴让Pandas使用NaN为较短的条目填充这些列.

Any way to overcome this? I am happy to have Pandas use NaN to pad those columns for the shorter entries.

推荐答案

在Python 3.x中:

In [6]: d = dict( A = np.array([1,2]), B = np.array([1,2,3,4]) )

In [7]: pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in d.items() ]))
Out[7]: 
    A  B
0   1  1
1   2  2
2 NaN  3
3 NaN  4

在Python 2.x中:

d.items()替换为d.iteritems().

这篇关于从条目长度不同的字典创建数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆