Search code examples
pythonpandasone-hot-encoding

How to print only the first and last 5?


I would like to print the first and last 5 of my one hot encoding data. The code is below. When it prints the first and last 30 are printed.

Code:

from random import randint
import pandas_datareader.data as web
import pandas as pd
import datetime 
import itertools as it
import numpy as np
import csv

df = pd.read_csv('C:Users\GrahamFam\Desktop\Data Archive\Daily3mid(Archive).txt')
df.columns = ['Date','b1','b2','b3']
df = df.set_index('Date')

reversed_df = df.iloc[::-1]

n=5
#print(reversed_df.drop(df.index[n:-n]))

df = pd.read_csv('C:Users\GrahamFam\Desktop\Data Archive\Daily3eve(Archive).txt')
df.columns = ['Date','b1','b2','b3']
df = df.set_index('Date')

reversed_df = df.iloc[::-1]

n=5
print(reversed_df.drop(df.index[n:-n]),("\n"))

BallOne = pd.get_dummies(reversed_df.b1)
BallTwo = pd.get_dummies(reversed_df.b2)
BallThree = pd.get_dummies(reversed_df.b3)
print(BallOne)
print(BallTwo)
print(BallThree)

Solution

  • If you're fine displaying the tail before the head, then can use np.r_ slicing from negative to positive:

    import pandas as pd
    import numpy as np
    df = pd.DataFrame(list(range(30)))
    
    df.iloc[np.r_[-3:3]]
    #     0
    #27  27
    #28  28
    #29  29
    #0    0
    #1    1
    #2    2
    

    Otherwise slice explicitly:

    n = 3
    l = len(df)
    df.iloc[np.r_[0:n, l-n:l]]
    #     0
    #0    0
    #1    1
    #2    2
    #27  27
    #28  28
    #29  29