repl.it
@sidonduarte/

pandas-head-tail

Python

Tail and Head in pandas

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
##
# By Sidon
# Resposta no STOpt  
# https://pt.stackoverflow.com/a/367662/7412
##

import pandas as pd

dados = [['22828949', '2019-02-26', '453.00'],
 ['22828949', '2019-02-22', '453.00'],
 ['22828949', '2019-02-18', '453.00'],
 ['22828949', '2019-02-05', '453.00'],
 ['22828950', '2019-02-26', '189.00'],
 ['22828950', '2019-02-24', '189.00']]

# Construindo o dataframe
df0 = pd.DataFrame(dados, columns=['ID', 'DT_DATE', 'NR_PRICE']).sort_values(by=['DT_DATE'])

# Removendo as datas duplicatas
df1 = df0.drop_duplicates(subset='DT_DATE', keep='last')

# Extraindo o primeiro, o último e o penultimo registros
df2 = df1.head(1).append(df1.tail(2))

# Apresentando o resultado
print(df2)