簡體   English   中英

numpy.ndarray 到數據幀轉換 - 維度問題

[英]numpy.ndarray to dataframe conversion - dimension issues

我正在嘗試將數組轉換為df ,並使用從another_df復制的索引。

another_df:
        test1               test2               test3               test4               test5
test1   0.0                 0.8                 0.6                 0.6                 0.2857142857142857
test2   0.8                 0.0                 0.5                 1.0                 0.8571428571428571
test3   0.6                 0.5                 0.0                 1.0                 0.7142857142857143
test4   0.6                 1.0                 1.0                 0.0                 0.7142857142857143
test5   0.2857142857142857  0.8571428571428571  0.7142857142857143  0.7142857142857143  0.0

print (array)
[[ 0.23052147  0.03058967]
 [-0.54449458 -0.08481665]
 [-0.21274323 -0.39635658]
 [ 0.13880332  0.58125618]
 [ 0.38791301 -0.13067262]]

print (type(array))
<class 'numpy.ndarray'>

df = pd.DataFrame(array, 
                  index = another_df.index, 
                  columns = ['x','y'])

它做得很好 - df是:

        x                   y
test1   0.2305214680511617  0.03058967262464556
test2   -0.544494575705709  -0.08481665342258861
test3   -0.2127432294443813 -0.396356582859552
test4   0.13880332309442767 0.5812561804072454
test5   0.38791301400450073 -0.13067261674975036

但是,我也得到ValueError: Shape of passed values is (5, 1), indices imply (5, 2) 這非常令人困惑,因為

(i) 盡管出現錯誤,但我的函數仍能正常完成,根據堆棧跟蹤發生在任何 return 語句之前。

(ii) 我的數組看起來是 2d,所以我不確定為什么它被讀取為 1d(這看起來正在發生)。

關於上述任何想法,我可以忽略它,因為它似乎恢復正常了嗎?

編輯 - 變量錯別字

(i) 盡管出現錯誤,但我的函數仍能正常完成,根據堆棧跟蹤發生在任何 return 語句之前。

如果語句在將數據幀設置為df變量之前引發異常,則不可能。 后者可能應該在您的代碼中更早地定義。 df = pd.DataFrame(array, ...)之前嘗試del df

(ii) 我的數組看起來是 2d,所以我不確定為什么它被讀取為 1d(這看起來正在發生)。

您的數據確實是二維的,但這不是問題。 正如@MycchakaKleinbort 所建議的,您應該使用another_df.index.shape檢查another_df索引的形狀。

否則你的代碼應該工作:

array = np.array([[ 0.23052147,  0.03058967],
                  [-0.54449458, -0.08481665],
                  [-0.21274323, -0.39635658],
                  [ 0.13880332,  0.58125618],
                  [ 0.38791301, -0.13067262]])

df = pd.DataFrame(array, 
                  index=['test1', 'test2', 'test3', 'test4', 'test5'], 
                  columns=['x', 'y'])
print(df)

# Output:
              x         y
test1  0.230521  0.030590
test2 -0.544495 -0.084817
test3 -0.212743 -0.396357
test4  0.138803  0.581256
test5  0.387913 -0.130673

數據框形狀:

>>> df.shape, df.index.shape, df.columns.shape
((5, 2), (5,), (2,))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM