2016-12-26 42 views
2

當我嘗試創建一個列表,然後數組中的熊貓數據框,我得到一個錯誤:創建從列表,然後數組中的熊貓數據幀產生錯誤

print(DataFrame([[10,20,30],np.arange(3)])) 

類型錯誤:預計名單,得到了numpy的.ndarray

但是,如果我扭轉了數據的順序,那麼操作成功:

print(DataFrame([np.arange(3),[10,20,30]])) 

你能解釋一下爲什麼?

回答

1

這可以給你一個粗略的想法。數據參數有多個檢查。如果數據參數是項目列表,那麼下面的代碼將在後臺執行。列表的第一個元素被檢查。如果它是一個列表,那麼它會進入列表式塊,但是如果它的ndarray進入了ndarray塊。列表塊不能處理ndarray,但ndarray塊可以處理列表。這就是爲什麼你沒有得到錯誤。

elif isinstance(data, (list, types.GeneratorType)): 
    if isinstance(data, types.GeneratorType): 
     data = list(data) 
    if len(data) > 0: 
-------> #IF FIRST ELEMENT IS LIST ENTER THIS BLOCK 
     if is_list_like(data[0]) and getattr(data[0], 'ndim', 1) == 1: 
      if is_named_tuple(data[0]) and columns is None: 
       columns = data[0]._fields 
      arrays, columns = _to_arrays(data, columns, dtype=dtype) 
      columns = _ensure_index(columns) 

      # set the index 
      if index is None: 
       if isinstance(data[0], Series): 
        index = _get_names_from_index(data) 
       elif isinstance(data[0], Categorical): 
        index = _default_index(len(data[0])) 
       else: 
        index = _default_index(len(data)) 

      mgr = _arrays_to_mgr(arrays, columns, index, columns, 
           dtype=dtype) 
------> #ELSE ENTER THIS BLOCK 
     else: 
      mgr = self._init_ndarray(data, index, columns, dtype=dtype, 
            copy=copy) 
    else: 
     mgr = self._init_dict({}, index, columns, dtype=dtype) 
+0

非常感謝您的澄清。 :) – Royalblue

+0

但是,我很好奇,如果從邏輯上(計算機語言理論上)可能允許第二個語法表示第一個語法。 – Royalblue

+0

@Royalblue \t沒有得到你。語言是由人類設計的,它將完全按照它的要求進行。你可以在語言規則的範圍內做任何事情。 – MYGz