gpt4 book ai didi

python - 将 0/1 添加到数据框行的每一列的所有排列

转载 作者:太空宇宙 更新时间:2023-11-04 00:04:53 24 4
gpt4 key购买 nike

对于我的数据框的每一行(例如 A 1 2 3 4 5),我想生成所有可能的 2^5 行排列,其中每列添加 0 或 1,不重复。

即我想生成 [0,1] 的所有长度为 5 的排列,例如[1,0,0,0,0], [0,1,0,0,0], [1,1,0,0,0] 作为向量,然后将它们添加到行。

上述示例的期望输出:

A 2 2 3 4 5  <<only first column added>>
A 1 3 3 4 5 <<only second column added>>
A 2 3 3 4 5 <<first and second columns added>>

最佳答案

您可以使用 itertools包生成所有可能的组合:itertools.product 生成一个可迭代对象,您可以将其转换为列表,然后转换为 Dataframe(非常欢迎提出防止转换的建议)

x = pd.DataFrame(list((itertools.product([0, 1], repeat=5))))
x.head()
Out[46]:
0 1 2 3 4
0 0 0 0 0 0
1 0 0 0 0 1
2 0 0 0 1 0
3 0 0 0 1 1
4 0 0 1 0 0
5 0 0 1 0 1
6 0 0 1 1 0
7 0 0 1 1 1

在下一步中,您可以将列表添加到数据框的每一行

comb = x + [1,2,3,4,5]
comb.head()
Out[47]:
0 1 2 3 4
0 1 2 3 4 5
1 1 2 3 4 6
2 1 2 3 5 5
3 1 2 3 5 6
4 1 2 4 4 5
5 1 2 4 4 6
6 1 2 4 5 5

关于python - 将 0/1 添加到数据框行的每一列的所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54477578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com