简体   繁体   English

用循环的输出填充数据框

[英]Fill a dataframe with the output of a loop

I'm trying to concatenate the output of a loop into dataframe.我正在尝试将循环的输出连接到数据帧中。 This example is totally unrealistic, but just to try to demonstrate my problem, my error and the result I need.这个例子是完全不切实际的,只是为了展示我的问题、我的错误和我需要的结果。

for a in range(1,4):

    list1 = ["22", "23", "24", "25"]
    list2 = ["a", "b", "c", "d"]
    
    df = pd.DataFrame({'Num': list1,'Alpha': list2})

    print(df)

My output:我的输出:

在此处输入图像描述

Good output良好的输出

   Num Alpha
0  22     a
1  23     b
2  24     c
3  25     d
4  22     a
5  23     b
6  24     c
7  25     d
8  22     a
9  23     b
10 24     c
11 25     d

This is one way to do it using your code above.这是使用上面的代码执行此操作的一种方法。 Create an empty list before your for loop and append the df to it.在 for 循环之前创建一个空列表并将 df 附加到它。 Then concat the final list.然后连接最终列表。

l = []   

for a in range(1,4):
    list1 = ["22", "23", "24", "25"]
    list2 = ["a", "b", "c", "d"]
    
    df = pd.DataFrame({'Num': list1,'Alpha': list2})

    l.append(df)

df = pd.concat(l)

Use pd.concat with *3 instead of looping through a range of 3:pd.concat*3一起使用,而不是在 3 范围内循环:

import pandas as pd
list1 = ["22", "23", "24", "25"]
list2 = ["a", "b", "c", "d"]
df = pd.concat([pd.DataFrame({'Num': list1,'Alpha': list2})] * 3).reset_index(drop=True)
df
Out[1]: 
   Num Alpha
0   22     a
1   23     b
2   24     c
3   25     d
4   22     a
5   23     b
6   24     c
7   25     d
8   22     a
9   23     b
10  24     c
11  25     d

You can do你可以做

l = []
for a in range(1, 4):
    
    list1 = ["22", "23", "24", "25"]
    list2 = ["a", "b", "c", "d"]
    l.append(pd.DataFrame({'Num': list1, 'Alpha': list2}))
out = pd.concat(l,ignore_index = True)

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

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