簡體   English   中英

從 while 循環返回 pandas dataframe

[英]Return a pandas dataframe from a while loop

我有一個 while 循環,它從列表中隨機返回三個項目。 然后再次執行相同操作,直到列表為空。 我想在 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)

我的目標是從 while 循環返回一個 pandas dataframe 有四列和 16 行。

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

我不知道如何讓一個while循環返回這樣一個dataframe。 任何幫助將非常感激。

您的問題中沒有指定幾件事,例如:

  • 是否必須使用while循環?
  • 您談論每行 3 個項目,然后在您沒有價值的dataframe中添加另一列(談論該store列)。

將第一個作為“是”,將第二個作為“第一列將是另一個值,您將 append 對您的代碼進行一些修改”,一個選項將是:

  1. 生成一個包含要加載到 dataframe 的數據的列表。
  2. 生成 dataframe 作為源。 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM