【问题标题】:Return a pandas dataframe from a while loop从 while 循环返回 pandas 数据帧
【发布时间】:2021-04-22 01:37:38
【问题描述】:

我有一个 while 循环,它从列表中随机返回三个项目。然后再次执行相同操作,直到列表为空。我想在 pandas 数据框中收集所有这 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 循环返回这样的数据帧。任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas while-loop


    【解决方案1】:

    您的问题中没有指定一些内容,例如:

    • 是否必须使用while 循环?
    • 您谈论每行 3 项,然后在您的 dataframe 中添加另一列您没有值(谈论该 store 列)。

    将第一个作为“是”,将第二个作为“第一列将是另一个值,您将对代码进行一些修改”,一个选项是:

    1. 使用要加载到数据框的数据生成一个列表。
    2. 以它为源生成数据帧。数据框列的数量必须与传入数据中可用的数据宽度相同。
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-17
      • 2012-06-26
      • 1970-01-01
      • 2021-11-13
      • 2015-11-17
      • 1970-01-01
      • 2020-08-06
      相关资源
      最近更新 更多