如何在Python的for循环中从np.array创建数据框架

huangapple go评论65阅读模式
英文:

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]])

huangapple
  • 本文由 发表于 2023年4月4日 05:50:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75924020.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定