我有兩個 numpy 陣列的串列,如下所示:
a_b = [array([0.23078484, 0.23076418]),
array([0.3478484, 0.72076418]),
array([1.42590463, 1.42562456])]
c_d = [array([0.23276474, 0.23276488]),
array([0.3498484, 0.72086418]),
array([1.43590464, 1.44562477])]
我想生成一個如下所示的 csv 檔案
Source A B C
a_b 0.23078484 0.3478484 1.42590463
a_b 0.23076418 0.72076418 1.42562456
c_d 0.23276474 0.3498484 1.43590464
c_d 0.23276488 0.72086418 1.44562477
到目前為止我已經嘗試過了
df = pd.DataFrame({'a_b': a_b , 'c_d': c_d}, columns = ['A', 'B','C'])
df.to_csv('test.csv', index=False)
但它給出了這個錯誤
raise ValueError("All arrays must be of the same length")
ValueError: All arrays must be of the same length
uj5u.com熱心網友回復:
您可以使用np.hstack T將陣列串列轉換為 numpy 陣列;將其轉換為 DataFrame;然后將其保存為 csv 檔案:
out = (pd.DataFrame(np.hstack((a_b, c_d)).T,
index=['a_b']*len(a_b[0]) ['c_d']*len(c_d[0]),
columns=[*'ABC'])
.reset_index()
.rename(columns={'index':'Source'}))
out.to_csv('file.csv')
與您類似的另一種方法是使用from_dict帶有“orient”引數的建構式。然后explode-ing 列將獲得預期的結果:
out = (pd.DataFrame.from_dict({'a_b': a_b , 'c_d': c_d},
orient='index',
columns = ['A', 'B','C'])
.explode(['A','B','C'])
.reset_index()
.rename(columns={'index':'Source'}))
輸出:
Source A B C
0 a_b 0.230785 0.347848 1.425905
1 a_b 0.230764 0.720764 1.425625
2 c_d 0.232765 0.349848 1.435905
3 c_d 0.232765 0.720864 1.445625
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/424162.html
