Python Forum
looping through series, changing value and sorting - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: looping through series, changing value and sorting (/thread-8270.html)



looping through series, changing value and sorting - metalray - Feb-12-2018

Dear Python Experts,

I got a series that looks the following:

9 71
14 1990
10 85

I want to append 19 to the 2 digit numbers and
then sort by index so it should be

1 1
2 3
3 2

So far I managed to loop through the series but somehow the series values dont change.

def years():
    for n in nonan:
        if len(n)<3:
            n='19'+n

    #nonan.sort_values(axis=0,ascending=False, inplace=True)
    return nonan
years()



RE: looping through series, changing value and sorting - Larz60+ - Feb-12-2018

Quote:then sort by index so it should be

1 1
2 3
3 2
Again please?


RE: looping through series, changing value and sorting - metalray - Feb-14-2018

Hi Larz60+,
Thanks for your reply.
Aside from adding the 19 to the strings of lengths 2
I want to sort them by their row number.

9 1971
14 1990
10 1985

the index (row number) would be

1 9 1971
2 14 1990
3 10 1985

sorted it would be

1 9 1971
3 10 1985
2 14 1990

and now a new index

1 1
2 3
3 2


RE: looping through series, changing value and sorting - kannanv110 - Feb-23-2018

Infile content
9 1971
14 1990
10 1985
24 1990
20 1985
19 1971

#!/usr/bin/python

with open('infile') as fd:
        years = []
        for line in fd.readlines():
                line.rstrip('\n')
                temp = line.split()[-1]
                if len(temp) == 2:
                        temp = '19'+temp
                years.append(temp)

yearsSorted = sorted(years)
newIndex = []
tempYears = {}

for year in yearsSorted:
        start = 0
        index = years.index(year)
        if tempYears.has_key(year):
                start = tempYears[year] + 1
        tempYears[year] = index
        newIndex.append(years.index(year,start))
i = 1
for index in newIndex:
        print i,index,years[index]
        i += 1
output
1 0 1971
2 5 1971
3 2 1985
4 4 1985
5 1 1990
6 3 1990