2

我有以下熊猫系列: output={'index':[0,1,2,3,4],'output'=[0,1,0,0,1]}

我想将输出列拆分为 2 列“0”和“1”:

index output 0 1
0     0      1 0
1     1      0 1
2     0      1 0
3     0      1 0
4     1      0 1

然后,我想删除输出列,只剩下 3 列:索引、0 和 1

我试过这个丑陋的代码:

for i in output:
    if i==0:
        output['0'],ouput['1']=1,0
    else:
        output['0'],ouput['1']=0,1

但它只在我的系列末尾添加了 2 行。

4

2 回答 2

1

numpy.whereDataFrame构造函数和广播布尔掩码一起使用:

output = pd.DataFrame({'index':[0,1,2,3,4],'output':[0,1,0,0,1]})

output[['0','1']]=pd.DataFrame(np.where((output['output'] == 0).values[:, None], [1,0], [0,1]))
print (output)
   index  output  0  1
0      0       0  1  0
1      1       1  0  1
2      2       0  1  0
3      3       0  1  0
4      4       1  0  1

如果输入首先由以下Series创建:DataFrameSeries.to_frame

s = pd.DataFrame({'index':[0,1,2,3,4],'output':[0,1,0,0,1]}).set_index('index')['output']
print (s)
index
0    0
1    1
2    0
3    0
4    1
Name: output, dtype: int64

df = s.to_frame()
df[['0','1']] = pd.DataFrame(np.where((s == 0).values[:, None], [1,0], [0,1]))
print (df)
       output  0  1
index              
0           0  1  0
1           1  0  1
2           0  1  0
3           0  1  0
4           1  0  1
于 2019-07-24T04:19:11.233 回答
1

IIUC,这就是你想要的:

result = pd.DataFrame({"0": (output == 0), "1": (output != 0)}, dtype=int)

如果输出系列只包含0and 1,你可以简单地做

result = pd.DataFrame({"0": 1 - output, "1": output})
于 2019-07-24T04:28:05.213 回答