python-3.x - 如何根据现有列将新列添加到 pandas 系列中

标签 python-3.x pandas dataframe

我有以下 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/

相关文章:

python - 如果循环 all() any() 就卡在 pandas 里了?

python - 如何检查 pandas 数据帧的列中的所有值是否相等?

python-3.x - 仅缺少数字 Weasyprint PDF

python - 继承 `int` 的类获得奇怪的幽灵般的变量赋值

python - 传递到另一个 if 语句时出现全局变量问题

python - 为什么不同 Pandas DataFrame 之间相同值的这些哈希值不同?

对于另一列的所有级别,R 通过一列的值提取第 n 个最低值

python-3.x - 如何绘制连接条形图顶部的线

python - 在 python 中使用 unique 函数时保持顺序

python - 权限错误: [Errno 13] Permission denied (after multiple successful writting attemps in the file)