python - 二值化数据框列并相应地拆分其他列值

标签 python pandas

df = pd.DataFrame({
    'x':[1,1,1,1,0,0,0,0,2,2,2,2],
    'y':[1.2,3.4,5.2,4.8,5.4,5.9,4.3,2.1,1.2,6.7,2.9,7.3]
})

我正在寻找一种根据 x 中的组对 x 进行二值化和拆分 y 的方法 这是我要实现的输出:

1  1.2  0  0    0  0
1  3.4  0  0    0  0 
1  5.2  0  0    0  0
1  4.8  0  0    0  0
0  0    1  5.4  0  0
0  0    1  5.9  0  0
0  0    1  4.3  0  0
0  0    1  2.1  0  0
0  0    0  0    1  1.2
0  0    0  0    1  6.7
0  0    0  0    1  2.9
0  0    0  0    1  7.3

为了实现上述结果,我基本上创建了新列 df2['x1'] = (df.x==1).astype(int), df2['y1']=df2.x1*df.y 等等 但我希望有更好的方法可以做到这一点

最佳答案

get_dummies

d = pd.get_dummies(df.x)
pd.concat(
    {'x': d, 'y': d.mul(df.y, axis=0)},
    axis=1
).swaplevel(0, 1, 1).sort_index(1)

    0       1       2     
    x    y  x    y  x    y
0   0  0.0  1  1.2  0  0.0
1   0  0.0  1  3.4  0  0.0
2   0  0.0  1  5.2  0  0.0
3   0  0.0  1  4.8  0  0.0
4   1  5.4  0  0.0  0  0.0
5   1  5.9  0  0.0  0  0.0
6   1  4.3  0  0.0  0  0.0
7   1  2.1  0  0.0  0  0.0
8   0  0.0  0  0.0  1  1.2
9   0  0.0  0  0.0  1  6.7
10  0  0.0  0  0.0  1  2.9
11  0  0.0  0  0.0  1  7.3

交错

不同的组合概念

from more_itertools import interleave

x = pd.get_dummies(df.x)
y = x.mul(df.y, 0)
x = x.add_prefix('x_')
y = y.add_prefix('y_')
x.join(y)[[*interleave(x, y)]]

    x_0  y_0  x_1  y_1  x_2  y_2
0     0  0.0    1  1.2    0  0.0
1     0  0.0    1  3.4    0  0.0
2     0  0.0    1  5.2    0  0.0
3     0  0.0    1  4.8    0  0.0
4     1  5.4    0  0.0    0  0.0
5     1  5.9    0  0.0    0  0.0
6     1  4.3    0  0.0    0  0.0
7     1  2.1    0  0.0    0  0.0
8     0  0.0    0  0.0    1  1.2
9     0  0.0    0  0.0    1  6.7
10    0  0.0    0  0.0    1  2.9
11    0  0.0    0  0.0    1  7.3

创意

i, u = pd.factorize(df.x)
r = np.arange(len(df))
out = np.zeros((len(df), len(u) * 2))
out[r, i * 2] = 1
out[r, i * 2 + 1] = df.y

pd.DataFrame(out, df.index)

      0    1    2    3    4    5
0   1.0  1.2  0.0  0.0  0.0  0.0
1   1.0  3.4  0.0  0.0  0.0  0.0
2   1.0  5.2  0.0  0.0  0.0  0.0
3   1.0  4.8  0.0  0.0  0.0  0.0
4   0.0  0.0  1.0  5.4  0.0  0.0
5   0.0  0.0  1.0  5.9  0.0  0.0
6   0.0  0.0  1.0  4.3  0.0  0.0
7   0.0  0.0  1.0  2.1  0.0  0.0
8   0.0  0.0  0.0  0.0  1.0  1.2
9   0.0  0.0  0.0  0.0  1.0  6.7
10  0.0  0.0  0.0  0.0  1.0  2.9
11  0.0  0.0  0.0  0.0  1.0  7.3

或者

i, u = pd.factorize(df.x)
r = np.arange(len(df))
out = np.zeros((len(df), len(u), 2))
out[r, i, 0] = 1
out[r, i, 1] = df.y

pd.DataFrame(out.reshape(len(df), -1), df.index)

关于python - 二值化数据框列并相应地拆分其他列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56228383/

相关文章:

python - NA 值的 pandas 损坏交叉表的干净替代品

python - 尝试从网页解析信息时出现 HTTPError

python - 如何与 Python 中的另一个程序交互?

python - opencv中的阈值化图片

python - 使用 __iter__ 迭代类实例

python - 评估 Pandas DataFrame 中的 bool 表达式

python - 我们如何合并多个图?

python - 属性错误 : 'module' object has no attribute 'DefaultRoutingSearchParameters'

python - Pandas NLTK 标记 "unhashable type: ' 列表'"

python - 为什么随机抽样与数据集而不是样本量成比例? ( Pandas .sample() 示例)