Python Forum
looping through series, changing value and sorting
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
looping through series, changing value and sorting
#1
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()
Reply
#2
Quote:then sort by index so it should be

1 1
2 3
3 2
Again please?
Reply
#3
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
Reply
#4
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Convert quarterly time series to monthly time series donnertrud 1 5,103 May-22-2020, 10:16 AM
Last Post: pyzyx3qwerty
  Sorting a copied list is also sorting the original list ? SN_YAZER 3 2,996 Apr-11-2019, 05:10 PM
Last Post: SN_YAZER

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020