python - 除了 for 循环之外更好的方法,

标签 python python-3.x pandas

我想创建一个包含 feature1monthfeature_segment 列的 DataFrame。我在 feature1 和 3 个 feature_segments 中有超过 3,000 个唯一值,我现在必须将每个功能映射到每个月和 feature_segment

例如: feature1 = 1 因此映射应创建一个数据框,如下所示:

feature1      month       feature_Segment
1              1           1
1              1           2
1              1           3
1              2           1
1              2           2
1              2           3
1              3           1
1              3           2
1              3           3
1              4           1 
1              4           2
1              4           3
1              5           1
1              5           2
1              5           3
1              6           1
1              6           2
1              6           3
1              7           1
1              7           2
1              7           3 
1              8           1
1              8           2
1              8           3
1              9           1
1              9           2
1              9           3
1              10          1
1              10          2
1              10          3
1              11          1
1              11          2
1              11          3
1              12          1
1              12          2
1              12          3

现在有什么方法可以在不使用 for 循环的情况下创建此数据框吗?

所有 df 列都在列表中。

最佳答案

使用itertools.product :

from  itertools import product
feature = [1]
feature_Segment = [1,2,3]
month = range(1, 13)


df = pd.DataFrame(product(feature, month, feature_Segment), 
                  columns=['feature1','month','feature_Segment'])
print (df.head(10))
   feature1  month  feature_Segment
0         1      1                1
1         1      1                2
2         1      1                3
3         1      2                1
4         1      2                2
5         1      2                3
6         1      3                1
7         1      3                2
8         1      3                3
9         1      4                1

关于python - 除了 for 循环之外更好的方法,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61555034/

相关文章:

python - Discord.py 检查 Channel 是否为 DM

python - 我如何使用opencv实现居中剪切图像

python - 如何将嵌套字典转换为 defaultdict?

python - AES 256 字节以外(8 或 16)

python - 以科学计数法将带有科学计数法的文本文件读取到 Pandas 数据框

Python 将单行转置为列

python - 异常捕获甚至值是真的?

python - 深度复制所有函数参数

python - Pandas 多个条件下行之间的差异

python - 将 numpy 数组传递给 Cython