I’m trying to output data in multiple CSV files using a for loop using the following code:
import numpy as np
# read multiple files
def show_datasets(filenames):
n = len(filenames)
data=[]
for i in range(0, n):
data = np.loadtxt(filenames[i], delimiter=',', dtype=float)
return data, i
print(show_datasets(['data1.csv', 'data2.csv', 'data3.csv']))
But the it only shows the dataset for the first CSV file and I think the loop ends at i=0 because the return shows the data for data1.csv and then 0 but I don’t get why it doesn’t go through i = 1, i=2 or show the rest of the CSV file data?
What I’m getting:
(array([[ 7.98631, 16.82952, 19.65165],
[ 7.1446 , 10.41674, 3.81853],
[ 7.48549, 14.61958, 8.87193],
[ 8.66521, 14.14244, 10.10248],
[14.80968, 12.82048, 13.41792]]), 0)
What I want:
(array([[ 7.98631, 16.82952, 19.65165],
[ 7.1446 , 10.41674, 3.81853],
[ 7.48549, 14.61958, 8.87193],
[ 8.66521, 14.14244, 10.10248],
[14.80968, 12.82048, 13.41792]]), 0)
(array([[ 12.65900,13.22477,8.94481],
[ 7.11298,1.99820,8.49168],
[ 0.25181,9.79979,13.62024],
[ 8.66521, 14.14244, 10.10248],
[1.98336,1.42358,9.92036]]), 1)
(array([[ 7.98631, 16.82952, 19.65165],
[ 14.12714,8.03384,15.76423],
[ 13.78446,8.92194,15.08250],
[ 15.79836,6.28136,7.43691],
[17.93699,0.01700,10.15189]]), 2)
>Solution :
returnstatement is inside theloop, which causes the function toexitand return the data for the first CSV file in the list.
import numpy as np
def show_datasets(filenames):
n = len(filenames)
data = []
for i in range(n):
data.append(np.loadtxt(filenames[i], delimiter=',', dtype=float))
return data
# Pass your datasets as required
print(show_datasets(['data1.csv', 'data2.csv', 'data3.csv']))
- Created an empty list called data to store the loaded datasets and use
appendmethod to add each loaded dataset to the data list. - Move the
returnstatement outside the loop to ensure that all datasets are loaded before returning the final result.