[英]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
循环?dataframe
中添加另一列(谈论该store
列)。将第一个作为“是”,将第二个作为“第一列将是另一个值,您将 append 对您的代码进行一些修改”,一个选项将是:
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.