简体   繁体   English

从 while 循环返回 pandas dataframe

[英]Return a pandas dataframe from a while loop

I have a while loop that randomly returns three items from a list.我有一个 while 循环,它从列表中随机返回三个项目。 And then do the same again until the list is empty.然后再次执行相同操作,直到列表为空。 I would like to collect all these 16 rows in a pandas dataframe.我想在 pandas dataframe 中收集所有这 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)

I aim to return from the while loop a pandas dataframe with four columns and 16 rows.我的目标是从 while 循环返回一个 pandas dataframe 有四列和 16 行。

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

I don't seeam to be able to figure out how to get a while loop to return such a dataframe.我不知道如何让一个while循环返回这样一个dataframe。 Any help would be much appreciated.任何帮助将非常感激。

There are several things that you've not specified in your question, like:您的问题中没有指定几件事,例如:

  • Is using a while loop mandatory?是否必须使用while循环?
  • You talk about 3 items per row, then you add another column to your dataframe for which you don't have a value (talking about that store column).您谈论每行 3 个项目,然后在您没有价值的dataframe中添加另一列(谈论该store列)。

Taking the first one as "yes" and the second one as "the first column will be another value that you will append with some modification to your code", an option would be:将第一个作为“是”,将第二个作为“第一列将是另一个值,您将 append 对您的代码进行一些修改”,一个选项将是:

  1. Generate a single list with the data that you want to load to your dataframe.生成一个包含要加载到 dataframe 的数据的列表。
  2. Generate the dataframe with it as source.生成 dataframe 作为源。 Dataframe columns need to be the same amount than data width available in the incoming data. 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)

Execute it to get:执行得到:

      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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM