英文:
How to create data frame from np.array inside a for loop in Python
问题
import numpy as np
import pandas as pd
all_cases = np.array([])
for i in range(1, 4):
subSoil_array = [i, 2i, 3i]
case_i = np.append(subSoil_array, 100*i)
print(case_i)
#print (all_cases)
需要从上述循环创建一个数据框(3行4列)。第一行应该是:
1 2 3 100
最后一行应该是:
3 6 9 300
我尝试了一些代码行。没有成功。有什么建议吗?
英文:
import numpy as np
import pandas as pd
all_cases= np.array([])
for i in range(1, 4):
subSoil_array= [i, 2*i, 3*i]
case_i=np.append(subSoil_array, 100*i)
print(case_i)
#print (all_cases)
I need to create a data frame (3 rows- 4 columns) from the above for loop. The first row should be
1 2 3 100
and the last one:
3 6 9 300
I have tried some lines. No luck. Any advice, please?
答案1
得分: 1
In [tag:numpy] 不需要使用循环,而是使用广播的向量化代码。
在你的情况下:
arr = np.arange(1, 4)[:,None]*np.array([1, 2, 3, 100])
输出:
array([[ 1, 2, 3, 100],
[ 2, 4, 6, 200],
[ 3, 6, 9, 300]])
使用循环
使用一个列表来收集数值,然后使用 vstack
:
l = []
for i in range(1, 4):
subSoil_array= [i, 2*i, 3*i]
l.append(np.r_[subSoil_array, 100*i])
all_cases = np.vstack(l)
输出:
array([[ 1, 2, 3, 100],
[ 2, 4, 6, 200],
[ 3, 6, 9, 300]])
英文:
In [tag:numpy] you wouldn't use a loop but vectorial code with broadcasting.
In your case:
arr = np.arange(1, 4)[:,None]*np.array([1, 2, 3, 100])
Output:
array([[ 1, 2, 3, 100],
[ 2, 4, 6, 200],
[ 3, 6, 9, 300]])
with a loop
Use a list to collect the values and vstack
:
l = []
for i in range(1, 4):
subSoil_array= [i, 2*i, 3*i]
l.append(np.r_[subSoil_array, 100*i])
all_cases = np.vstack(l)
Output:
array([[ 1, 2, 3, 100],
[ 2, 4, 6, 200],
[ 3, 6, 9, 300]])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论