[英]Create Pandas dataframe from numpy array and use first column of the array as index
我有一個numpy數組(a):
array([[ 1. , 5.1, 3.5, 1.4, 0.2],
[ 1. , 4.9, 3. , 1.4, 0.2],
[ 2. , 4.7, 3.2, 1.3, 0.2],
[ 2. , 4.6, 3.1, 1.5, 0.2]])
我想在我的numpy數組的第一列創建一個prandas dataframe(pd),其中values = a,columns = A,B,C,D和index =,最后它應該如下所示:
A B C D
1 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
2 4.6 3.1 1.5 0.2
我在嘗試這個:
df = pd.DataFrame(a, index=a[:,0], columns=['A', 'B','C','D'])
我收到以下錯誤:
ValueError: Shape of passed values is (5, 4), indices imply (4, 4)
有幫助嗎? 謝謝
您將完整數組作為data
參數傳遞,如果只需要數組中的4列作為data
,則還需要對數組進行切片:
In [158]:
df = pd.DataFrame(a[:,1:], index=a[:,0], columns=['A', 'B','C','D'])
df
Out[158]:
A B C D
1 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
2 4.6 3.1 1.5 0.2
索引中也有重復值會使過濾/索引出現問題
所以這里a[:,1:]
我會根據需要從第1列開始獲取所有行但請參閱文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.