从while循环返回数据帧

2024-10-01 07:50:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个while循环,它从一个列表中随机返回三个项目。然后再次执行相同操作,直到列表为空。我想在一个数据帧中收集所有这16行

from random import randint

colors = ['Pink', 'Purple', 'Green', 'Skyblue', 'Blue', 'Grey'] * 8

while colors:
    lst = [colors.pop(randint(0, len(colors) - 1)) for _ in range(3)]
    print(lst)

我的目标是从while循环返回一个包含四列和16行的pandas数据帧

pd.DataFrame(index=np.arange(1,17), columns = ["Store", "Bar 1", "Bar 2", "Bar 3"])

我似乎不知道如何获得while循环来返回这样的数据帧。任何帮助都将不胜感激


Tags: 数据项目fromimport列表barrandomgreen
1条回答
网友
1楼 · 发布于 2024-10-01 07:50:15

有几件事你在问题中没有具体说明,比如:

  • 是否必须使用while循环
  • 您将讨论每行3个项目,然后向dataframe添加另一个没有值的列(讨论该store列)

将第一列视为“是”,第二列视为“第一列将是另一个值,您将在代码中添加一些修改”,选项如下:

  1. 生成一个包含要加载到数据帧的数据的列表
  2. 生成数据帧并将其作为源。Dataframe列的数量必须与传入数据中可用的数据宽度相同
import numpy as np
import pandas as pd
from random import randint

colors = ['Pink', 'Purple', 'Green', 'Skyblue', 'Blue', 'Grey'] * 8
data = []

while colors:
    lst = [colors.pop(randint(0, len(colors) - 1)) for _ in range(3)]
    data.append(lst)

myDataFrame = pd.DataFrame(data, columns = ["Bar 1", "Bar 2", "Bar 3"])

print(myDataFrame)

执行它以获得:

      Bar 1    Bar 2    Bar 3
0      Blue   Purple  Skyblue
1      Blue     Blue     Grey
2    Purple     Pink     Grey
3      Blue     Pink    Green
4     Green  Skyblue    Green
5      Pink     Pink     Grey
6      Pink   Purple    Green
7   Skyblue     Blue  Skyblue
8    Purple     Blue   Purple
9      Grey    Green  Skyblue
10    Green   Purple    Green
11     Grey    Green     Grey
12  Skyblue  Skyblue   Purple
13  Skyblue     Blue     Pink
14     Blue     Pink     Grey
15     Grey   Purple     Pink

相关问题 更多 >