對我來說,它的工作原理很好:
import pandas as pd
df1 = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6]}, index=['a','b','c'])
print (df1)
A B
a 1 4
b 2 5
c 3 6
print (df1.index.shape)
(3,)
df2 = df1.values
print (df2)
[[1 4]
[2 5]
[3 6]]
print (df2.shape)
(3, 2)
print (pd.DataFrame(df2,index=df1.index))
0 1
a 1 4
b 2 5
c 3 6
如果變化index
到columns
,它引發錯誤:
print (pd.DataFrame(df2,columns=df1.index))
ValueError: Shape of passed values is (2, 3), indices imply (3, 3)
它產生錯誤,如果index
長度是不同的:
import pandas as pd
df1 = pd.DataFrame({'A':[1,2],
'B':[3,4],
'C':[5,6]}, index=['a','b'])
print (df1)
A B C
a 1 3 5
b 2 4 6
idx = pd.Index([5,6,7])
print (idx)
Int64Index([5, 6, 7], dtype='int64')
print (idx.shape)
(3,)
df2 = df1.values
print (df2)
[[1 3 5]
[2 4 6]]
print (df2.shape)
(2, 3)
print (pd.DataFrame(df2,index=idx))
ValueError: Shape of passed values is (3, 2), indices imply (3, 3)