numpy 如何在python中的for循环中追加一个数组和每次迭代的结果?

bksxznpy  于 2023-10-19  发布在  Python
关注(0)|答案(2)|浏览(114)

如何在for循环中将每次迭代的结果追加到数组中?

data = np.array([])
for sheet in sheets:
    result = pd.read_excel(file_loc, sheet_name = sheet,usecols="Q").dropna()
    result = result.values.tolist()
    result = result[1:]
    print(result)

如果print(result)返回:

[1 , 2 , 3]

[4 , 5 , 6]

[7 , 8 , 9]

print(data)看起来像这样:

[[1 , 2 , 3],
 [4 , 5 , 6]
 [7 , 8 , 9]]
zpqajqem

zpqajqem1#

import numpy as np
import pandas as pd

data = np.array([])  # Initialize an empty array

for sheet in sheets:
    result = pd.read_excel(file_loc, sheet_name=sheet, usecols="Q").dropna()
    result = result.values.tolist()
    result = result[1:]
    print(result)
    
    if len(data) == 0:
        data = np.array(result)  # Assign the first result directly to the data array
    else:
        data = np.append(data, result, axis=0)  # Append subsequent results to the data array
        
print(data)
2nc8po8w

2nc8po8w2#

您可以使用vstack将结果作为新行添加到numpy 2d数组“data”中

import numpy as np
import pandas as pd

data = np.array([])  # Initialize an empty array

for sheet in sheets:
    result = pd.read_excel(file_loc, sheet_name=sheet, usecols="Q").dropna()
    result = result.values.tolist()
    result = result[1:]
    print(result)

    if len(data) == 0:
        data = np.array(result)
else:
        data = np.vstack((data, result)) 
    
print(data)

相关问题