0

I have a column of data which is like 20181,20182,20183,20184. I am wondering how to change them to the 2018Q1, 2018Q2 format or separate them into two columns one for years and the other for quarters.

2
  • does your last number in that numbers always lies in 1,2,3 and 4? like 20191, 20192. 20193 and 20194? Commented Jan 22, 2021 at 4:31
  • Are these numbers column name or values of a column? Commented Jan 22, 2021 at 4:32

2 Answers 2

1

Since years are in the foreseeable future always 4 characters long, you can simply split at the 4th character like this:

s = '20181'
year, quarter = s[:4], s[4:]
# You can now use year and quarter separately or merge them back in the given format:
print(year + 'Q' + quarter)
Sign up to request clarification or add additional context in comments.

1 Comment

If you expect to encounter years that are not 4 characters, you could use: year, quarter = s[:-1], s[-1:] 🙂
0

You can try this:

Adding character

Code Syntax

def subby(list):
    lista = []
    for each in list:
        string = str(each)
        part1, part2 = string[:4], string[-1:]
        lista.append((part1+'Q'+part2))
    return lista

print(subby([20181,20182,20183,20184]))

Output

['2018Q1', '2018Q2', '2018Q3', '2018Q4']

[Program finished]

converting to dictionary

Code Syntax

def dicty(list):
    dict = {"year":[],
                "quarter": []
                }
     
    for each in list:
        string = str(each)
        dict['year'].append(int(string[:4]))
        dict['quarter'].append(int(string[-1:]))
    
    return dict

print(dicty([20181,20182,20183,20184]))

Output

{'year': [2018, 2018, 2018, 2018], 'quarter': [1, 2, 3, 4]}

[Program finished]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.