'Pandas sorting, python CSV, using the position of a given value
'I'm living a little gram in the code.
I have a csv that has headers that don't always arrive with the same name.
id, casa, data de entrada, hora another time id, casa, data, hora
This csv has different versions and each version is distributed in a similar but not the same way, exe: id, data, casa, hora the date column can be in another position.
Having said that, I created:
contends of file1.csv
['1', '9992222', '123', '9912', '909', '2021-05-06', '10050', 'Test INICIAL','KG'],
['1', '9992222', '333', '9912', '909', '2021-04-03', '10052', 'Test2 INICIAL','KG'],
['1', '9992222', '143', '9912', '909', '2021-02-04', '10053', 'Test3 INICIAL','KG'],
['1', '9992222', '883', '9912', '909', '2021-03-01', '10054', 'Test5 INICIAL','KG'],
with open('file1.csv', 'r') as f:
f.readline()
r = f.__next__()
a = r.split(';')
for x in a:
if "-" in x:
at = x.split('-')
ano = len(at[0])
mes = len(at[1])
dia = len(at[2])
if ano == 4 and mes == 2 and dia == 2:
posicao = a.index(x)
dados = csv.reader(f, delimiter=";")
lista = list(dados)
lista_ordenada = sorted(lista, key=lambda dado: int(posicao), reverse=False)
for l in lista_ordenada:
print(l)
My doubt, I can do an ordering using the date but as can be seen I'm taking the position where the standard date is in the csv and from the position use the content to order the csv?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
