import pandas as pd
import numpy as np
zeros=np.zeros((6,6))
arra=np.array([zeros])
rownames=['A','B','C','D','E','F']
colnames=[['one','tow','three','four','five','six']]
df=pd.DataFrame(arra,index=rownames,columns=colnames)
print(df)
錯誤:ValueError:必須通過二維輸入。形狀=(1, 6, 6)
我想要的輸出是:
A B C D E F
one 0 0 0 0 0 0
tow 0 0 0 0 0 0
three 0 0 0 0 0 0
four 0 0 0 0 0 0
five 0 0 0 0 0 0
six 0 0 0 0 0 0
uj5u.com熱心網友回復:
試試這個
pd.DataFrame(np.zeros((6,6)), columns=list('ABCDEF'), index=['one','tow','three','four','five','six'])
uj5u.com熱心網友回復:
試試這個
zeros=np.zeros((6,6), dtype=int)
df=pd.DataFrame(zeros, columns=['A','B','C','D','E','F'], index=['one','tow','three','four','five','six'])
明白在你的問題'A','B','C','D','E','F'這些是列名和'one','tow','three','four','五','六' 是索引,您將它們與行和列混淆了。
你得到這個錯誤的原因是因為行 arra=np.array([zeros]) 它將二維陣列轉換為一維陣列(就像它在下面給出的那樣 - 參見 '[[[' 這意味著它是二維陣列的一維陣列),但您需要二維陣列來創建資料框。
array([[[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]]])
希望這有幫助!
uj5u.com熱心網友回復:
如果您想使用單個值初始化 DataFrame,則無需費心創建 2D 陣列,只需將所需的標量傳遞給 DataFrame 建構式,它將廣播:
import pandas as pd
rownames=['A','B','C','D','E','F']
colnames=[['one','tow','three','four','five','six']
df=pd.DataFrame(0, index=rownames, columns=colnames)
print(df)
輸出:
one tow three four five six
A 0 0 0 0 0 0
B 0 0 0 0 0 0
C 0 0 0 0 0 0
D 0 0 0 0 0 0
E 0 0 0 0 0 0
F 0 0 0 0 0 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/474484.html
上一篇:如何將一行0添加到資料框中
