'Getting modified data from an original data set, into a new 2D list, in the right rows and columns
Totally newbie here, but really want to learn. I am in a class where we are learning to use basics, like nested for-statements, so no pandas. And for this assignment, to hand in, we cannot import anything, only csv module to work with csv files. We cannot use max() nor min() nor sort() nor sorted().
So there is a big csv file, with countries and populations and years. Countries down the left column, years along the first row, and populations. Like 20 countries, 18 columns of years.
I have imported that csv file into my IDE, to a 2D list. Then I applied calculations to it to have min population, max population and population change. This data i now want to save into a new 2D list. THIS IS WHERE I get stuck.
#my own min() and max() defs.
def maxValue(listValues):
maximum = 0
for counter in listValues:
if counter > maximum:
maximum = counter
return maximum
def minValue(listValues):
minimum = listValues[0]
for counter in listValues:
if counter < minimum:
minimum = counter
return minimum
#convert the data in the 2D list into integers.
#I start at the second row, since first row is years,
#and start that the second column since first column is countries
for row in range(1, len(dataset)):
for column in range(1,len(dataset[row])):
dataset[row][column] = int(dataset[row][column])
#I go through data set, make calculations, and then try
# to append them to a new >listAnalyzed, which would
#have only 4 columns, with country, maxpop, minpop, popchange.
listAnalyzed = []
for row in dataset[1:]:
for colum in row:
maxPop = maxValue(row[1:])
minPop = minValue(row[1:])
chgPop = ((row[18] - row[1]) / row[1]) * 100
listAnalyzed.append(row[0])
listAnalyzed.append(maxPop)
listAnalyzed.append(minPop)
listAnalyzed.append(chgPop)
print(listAnalyzed)
But when I print listAnalyzed, I just get all the data in a single 1D list. I tried different combos, sometimes getting 18 rows in a 2D list, but all the data in the first row only. The more I messed with the code, the worst it got. So i stopped before it just got me more confused.
what I need is a 2D list with 18 rows, each row with 4 columns (country, max, min,change). How do I do it?
Thank you! Really chugging here :(
Solution 1:[1]
Your solution would look something like the following:
listAnalyzed = []
for row in dataset[1:]:
for column in row:
maxPop = maxValue(row[1:])
minPop = minValue(row[1:])
chgPop = ((row[18] - row[1]) / row[1]) * 100
listAnalyzed.append([row[0], maxPop, minPop, chgPop])
print(listAnalysed)
You just needed to add the required fields in a list and then append that list to your listAnalysed
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | enthusiast |
