我有一个 Pandas DataFrame df
来存储一些数值:
print(df)
value
0 0
1 2
2 4
3 5
4 8
我有一个函数可以将数值转换为 one-hot 向量
print(to_categorical(0))
[1 0 0 0 0 0 0 0 0 0]
print(to_categorical(5))
[0 0 0 0 0 5 0 0 0 0]
等等...
因此,我可以在数值列上调用我的函数:
print(to_categorical(df['value'))
[[1 0 0 0 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0 0 0]
[0 0 0 0 1 0 0 0 0 0]
[0 0 0 0 0 1 0 0 0 0]
[0 0 0 0 0 0 0 0 1 0]]
现在我想将结果存储为新列。这是我对示例的期望:
df['one-hot'] = to_categorical(df['value')
print(df)
value one-hot
0 0 [1 0 0 0 0 0 0 0 0 0]
1 2 [0 0 1 0 0 0 0 0 0 0]
2 4 [0 0 0 0 1 0 0 0 0 0]
3 5 [0 0 0 0 0 1 0 0 0 0]
4 8 [0 0 0 0 0 0 0 0 1 0]
但这给了我一个错误,因为 pandas 试图将我的数组展平为多个列。我怎样才能做到这一点?
最佳答案
首先,我认为在 pandas 中使用 list
不是 good idea ,但可以通过转换为列表来实现:
df['one-hot'] = to_categorical(df['value').tolist()
关于python - Pandas : Add arrays as values of column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55394558/