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.
-
does your last number in that numbers always lies in 1,2,3 and 4? like 20191, 20192. 20193 and 20194?Prakash Dahal– Prakash Dahal2021-01-22 04:31:27 +00:00Commented Jan 22, 2021 at 4:31
-
Are these numbers column name or values of a column?Prakash Dahal– Prakash Dahal2021-01-22 04:32:19 +00:00Commented Jan 22, 2021 at 4:32
Add a comment
|
2 Answers
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)
1 Comment
Jiří Baum
If you expect to encounter years that are not 4 characters, you could use:
year, quarter = s[:-1], s[-1:] 🙂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]