迭代创建 Pandas DataFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35612918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:45:32  来源:igfitidea点击:

Create pandas DataFrame iteratively

pythonpandasdataframe

提问by JoeBlack

I am creating the list as follows:

我正在创建列表如下:

myList = []
for i in range(0,10):
    val0 = 1  # some formula for obtaining values
    val1 = 2.5
    val2 = 1.8
    myList.append([val0,val1,val2])

How can I do the same loop for pandas DataFrame (i.e. myListmust be a DataFrame).

我怎样才能对 Pandas DataFrame 执行相同的循环(即myList必须是 a DataFrame)。

回答by sedavidw

Ideally you want to create your DataFrameonce you have all the data in place. Slightly modifying your example:

理想情况下,您希望在DataFrame拥有所有数据后创建自己的。稍微修改您的示例:

my_df = []
for i in range(0,10):
    d = {
        'val0' : 1,  # some formula for obtaining values
        'val1' : 2.5,
        'val2' : 1.8
    }
    my_df.append(d)

my_df = pd.DataFrame(my_df)

So now my_dfis a DataFramewith val0, val1and val2as columns

所以现在my_dfDataFramewith val0, val1and val2as 列

回答by MaxU

if i got your question right:

如果我问对了你的问题:

import pandas as pd

myList = []

for i in range(0,10):
    val0 = 1  # some formula for obtaining values
    val1 = 2.5
    val2 = 1.8
    myList.append([val0,val1,val2])

df = pd.DataFrame(myList, columns=['val0','val1','val2'])
print(df)

PS you don't want to do append data to the DataFrame in the loop - it won't be very efficient.

PS,您不想在循环中将数据附加到 DataFrame - 它不会非常有效。

Output:

输出:

   val0  val1  val2
0     1   2.5   1.8
1     1   2.5   1.8
2     1   2.5   1.8
3     1   2.5   1.8
4     1   2.5   1.8
5     1   2.5   1.8
6     1   2.5   1.8
7     1   2.5   1.8
8     1   2.5   1.8
9     1   2.5   1.8