我有一個 (3*1) 形式的 NumPy 陣列:
['1 2 3', '4 5 6 7 8 9', '10 11 12 13'].
每一行都是特征值的集合,每一行都有不同數量的特征。如何將此陣列拆分為多列,每列代表所有行的一個特征?
更新:我現在在 DataFrames 上使用。所以,我有一個包含一列的資料框。想要擴展它并將其轉換為整數。我怎樣才能做到這一點?

期望:我想將每一行中的資料拆分為多列(特征)。然后,將每一列改為數字。
uj5u.com熱心網友回復:
你可以 expand=True像str.split下面這樣使用:
df = pd.DataFrame({'features':['191 367 614 634 711',
'1202 1220 131 1730 2281 2572 2602 2611 2824',
'2855 2940 3149 3313 3560 3568 3824 4185 4266']})
df.features.str.split(expand=True).astype(float).add_prefix('feature_')
輸出:
feature_0 feature_1 feature_2 ... feature_6 feature_7 feature_8
0 191.0 367.0 614.0 ... NaN NaN NaN
1 1202.0 1220.0 131.0 ... 2602.0 2611.0 2824.0
2 2855.0 2940.0 3149.0 ... 3824.0 4185.0 4266.0
uj5u.com熱心網友回復:
由于 numpy 不支持非矩形陣列,因此使用 pandas 最簡單:
df = pd.concat([pd.Series(l) for l in pd.Series(a).str.split(' ').tolist()], axis=1).T.add_prefix('feature_')
輸出:
>>> df
feature_0 feature_1 feature_2 feature_3 feature_4 feature_5
0 1 2 3 NaN NaN NaN
1 4 5 6 7 8 9
2 10 11 12 13 NaN NaN
uj5u.com熱心網友回復:
您顯示一個串列(但如果它是一個字串陣列,則以下內容也適用):
In [44]: alist = ['1 2 3', '4 5 6 7 8 9', '10 11 12 13']
In [45]: alist
Out[45]: ['1 2 3', '4 5 6 7 8 9', '10 11 12 13']
將每個字串拆分為一個串列:
In [46]: blist = [s.split() for s in alist]
In [47]: blist
Out[47]: [['1', '2', '3'], ['4', '5', '6', '7', '8', '9'], ['10', '11', '12', '13']]
將每個數字字串轉換為 int:
In [48]: clist = [[int(x) for x in s] for s in blist]
In [49]: clist
Out[49]: [[1, 2, 3], [4, 5, 6, 7, 8, 9], [10, 11, 12, 13]]
由于子串列的長度不同,我將避免將其作為陣列處理。如果您指定這樣的串列串列如何映射到您的功能概念,我們可以繼續。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/445128.html
