Python3 *:从列表中创建一个pandas数据帧

时间:2018-02-15 06:15:48

标签: python-3.x pandas

我试图从列表中创建熊猫数据框,如下所示:

my_value = ['Aberarder Creek', 'Town of Plympton-Wyoming', 'Aylmer', '17-4091-
47723', '43.062, -82.109', 'Northern Pike Rock Bass Smallmouth Bass White 
Sucker']
df = pd.DataFrame(columns=['Lake Name','Municipality','MNRF 
District','Coordinates','Waterbody ID','Fish Species'],index=np.arange(0))
my_df = pd.DataFrame(my_value,columns=['Lake Name','Municipality','MNRF 
District','Coordinates','Waterbody ID','Fish Species'])
my_df.append(df,ignore_index=True)
df

保持geeting错误消息,例如:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in 
create_block_manager_from_blocks(blocks, axes)
   4293                 blocks = [make_block(values=blocks[0],
-> 4294                                      placement=slice(0, 
len(axes[0])))]
   4295 

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in 
make_block(values, placement, klass, ndim, dtype, fastpath)
   2718 
-> 2719     return klass(values, ndim=ndim, fastpath=fastpath, 
placement=placement)
   2720 

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in 
__init__(self, values, ndim, fastpath, placement, **kwargs)
   1843         super(ObjectBlock, self).__init__(values, ndim=ndim, 
fastpath=fastpath,
-> 1844                                           placement=placement, **kwargs)
   1845 

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in __init__(self, values, placement, ndim, fastpath)
    114                              'implies %d' % (len(self.values),
--> 115                                              len(self.mgr_locs)))
    116 

ValueError: Wrong number of items passed 1, placement implies 6

我想知道my_value中的元素如何与列数不匹配。 如此困惑,我可能会对熊猫基础知识产生一些误解,谢谢!

1 个答案:

答案 0 :(得分:4)

对于包含多列[]的一行的嵌套列表,您需要DataFrame

my_df = pd.DataFrame([my_value],columns=['Lake Name','Municipality','MNRF District','Coordinates','Waterbody ID','Fish Species'])
print (my_df)
         Lake Name              Municipality MNRF District    Coordinates  \
0  Aberarder Creek  Town of Plympton-Wyoming        Aylmer  17-4091-47723   

      Waterbody ID                                       Fish Species  
0  43.062, -82.109  Northern Pike Rock Bass Smallmouth Bass White ...