Filling dict with NA values to allow conversion to pandas dataframe

最后都变了- 提交于 2019-11-30 11:51:50

Another option is to use from_dict with orient='index' and then take the tranpose:

my_dict = {'a' : [1, 2, 3, 4, 5], 'b': [1, 2, 3]}
df = pd.DataFrame.from_dict(my_dict, orient='index').T

Note that you could run into problems with dtype if your columns have different types, e.g. floats in one column, strings in another.

Resulting output:

     a    b
0  1.0  1.0
1  2.0  2.0
2  3.0  3.0
3  4.0  NaN
4  5.0  NaN
#dictionary of different lengths...
my_dict = {'a' : [1, 2, 3, 4, 5], 'b': [1, 2, 3]}
pd.DataFrame(dict([(col_name,pd.Series(values)) for col_name,values in my_dict.items() ]))

Output -

   a    b
0  1  1.0
1  2  2.0
2  3  3.0
3  4  NaN
4  5  NaN

With itertools (Python 3):

import itertools
pd.DataFrame(list(itertools.zip_longest(*d.values())), columns=d.keys()).sort_index(axis=1)
Out[728]: 
   col1  col2  col3  col4  col5
0   5.0    12   1.0 -15.0  10.0
1   7.0     0   9.0  11.0   7.0
2   NaN     6   1.0   2.0  18.0
3   NaN     9   8.0  10.0   NaN
4   NaN    -4   NaN   7.0   NaN
5   NaN   -11   NaN  -1.0   NaN
6   NaN     6   NaN   NaN   NaN

Here's an approach using masking -

K = d.keys()
V = d.values()

mask = ~np.in1d(K,'Date')
K1 = [K[i] for i,item in enumerate(V) if mask[i]]
V1 = [V[i] for i,item in enumerate(V) if mask[i]]

lens = np.array([len(item) for item in V1])
mask = lens[:,None] > np.arange(lens.max())

out_arr = np.full(mask.shape,np.nan)
out_arr[mask] = np.concatenate(V1)
df = pd.DataFrame(out_arr.T,columns=K1,index=d['Date'])

Sample run -

In [612]: d.keys()
Out[612]: ['col4', 'col5', 'col2', 'col3', 'col1', 'Date']

In [613]: d.values()
Out[613]: 
[[-15, 11, 2, 10, 7, -1],
 [10, 7, 18],
 [12, 0, 6, 9, -4, -11, 6],
 [1, 9, 1, 8],
 [5, 7],
 ['01-01-15',
  '01-02-15',
  '01-03-15',
  '01-04-15',
  '01-05-15',
  '01-06-15',
  '01-07-15']]

In [614]: df
Out[614]: 
          col4  col5  col2  col3  col1
01-01-15   -15    10    12     1     5
01-02-15    11     7     0     9     7
01-03-15     2    18     6     1   NaN
01-04-15    10   NaN     9     8   NaN
01-05-15     7   NaN    -4   NaN   NaN
01-06-15    -1   NaN   -11   NaN   NaN
01-07-15   NaN   NaN     6   NaN   NaN
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!