Pandas - get first n-rows based on percentage

Mohamed Thasin ah picture Mohamed Thasin ah · May 4, 2018 · Viewed 13.4k times · Source

I have a dataframe i want to pop certain number of records, instead on number I want to pass as a percentage value.

for example,

df.head(n=10)

Pops out first 10 records from data set. I want a small change instead of 10 records i want to pop first 5% of record from my data set. How to do this in pandas.

I'm looking for a code like this,

df.head(frac=0.05)

Is there any simple way to get this?

Answer

Mihai Alexandru-Ionut picture Mihai Alexandru-Ionut · May 4, 2018

I want to pop first 5% of record

There is no built-in method but you can do this:

You can multiply the total number of rows to your percent and use the result as parameter for head method.

n = 5
df.head(int(len(df)*(n/100)))

So if your dataframe contains 1000 rows and n = 5% you will get the first 50 rows.