迭代创建 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
Create pandas DataFrame iteratively
提问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. myList
must be a DataFrame
).
我怎样才能对 Pandas DataFrame 执行相同的循环(即myList
必须是 a DataFrame
)。
回答by sedavidw
Ideally you want to create your DataFrame
once 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_df
is a DataFrame
with val0
, val1
and val2
as columns
所以现在my_df
是DataFrame
with val0
, val1
and val2
as 列
回答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