我有以下 Pandas 系列:
output={'index':[0,1,2,3,4],'output'=[0,1,0,0,1]}
我想将输出列拆分为“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 行。
最佳答案
使用numpy.where
使用 DataFrame
构造函数和广播 bool 掩码:
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
,首先通过Series.to_frame
创建DataFrame
:
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
关于python-3.x - 如何根据现有列将新列添加到 pandas 系列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57175153/