我正在使用PySpark,并试图使用CSV来存储我的数据。我把我的Numpy数组转换成了DataFrame,它的格式是这样的:
label | 0 1 2 4 ... 768
---------------------------------------
1 | 0.12 0.23 0.31 0.72 ... 0.91
依此类推,将数组中"行向量"本身的每个值拆分为单独的列。该格式与Spark不兼容,它需要一列features
。有没有一种方法可以将我的数组加载到那种格式的DataFrame中?例如:
label | Features
------------------------------------------
1 | [0.12,0.23,0.31,0.72,...,0.91]
我试着遵循这个线程的建议,其中详细说明了使用Spark API合并列,但当在中加载标签时,我得到了一个错误,因为标签变成了向量的一部分,而不是string
或int
值。
我对spark一无所知,但如果你想要一个带有列表列的数据帧,只需执行df['features'] = SOME_2D_LIST_OF_LISTS
data = [[1,2,3],[4,5,6],[7,8,9]]
df = pd.DataFrame()
df['Features'] = data # now you have a column of lists
# If for whatever reason you want each row value to itself be a numpy array add
df['Features'] = df['Features'].map(np.array)
如果数据已经是一个numpy数组,只需执行CCD_ 5。
应该做到这一点,请注意,为了更好的可读性,我决定使用整数而不是浮点:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(20, 30, size=30).reshape(3, 10))
df.insert(0, "label", [1,2,3])
print(df)
label 0 1 2 3 4 5 6 7 8 9
0 1 26 27 25 29 20 23 26 25 22 23
1 2 20 20 26 25 23 23 26 24 27 23
2 3 24 22 24 22 26 23 27 22 26 23
选择所有的功能列(我在这里使用了iloc
(,并将它们转换为列表列表。
features = df.iloc[:, 1:].to_numpy().tolist()
print(features)
[[26, 27, 25, 29, 20, 23, 26, 25, 22, 23],
[20, 20, 26, 25, 23, 23, 26, 24, 27, 23],
[24, 22, 24, 22, 26, 23, 27, 22, 26, 23]]
然后用你的标签和新功能制作一个新的数据帧:
new_df = pd.DataFrame({
"label": df["label"],
"features": features
})
print(new_df)
label features
0 1 [26, 27, 25, 29, 20, 23, 26, 25, 22, 23]
1 2 [20, 20, 26, 25, 23, 23, 26, 24, 27, 23]
2 3 [24, 22, 24, 22, 26, 23, 27, 22, 26, 23]