熊猫:添加数组作为列的值

时间:2019-03-28 09:49:52

标签: python pandas

我有一个存储一些数值的Pandas DataFrame df

print(df)

       value 
0          0
1          2
2          4
3          5
4          8

我有一个将数值转换为一键向量的函数

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]

但是这给我一个错误,因为熊猫试图将我的数组展平为多个列。我该怎么办?

1 个答案:

答案 0 :(得分:2)

首先,我认为在good idea中使用list大熊猫不是可行的,但可以通过转换为列表来实现:

df['one-hot'] = to_categorical(df['value').tolist()