Tuesday, 5 September 2023

Pandas: Get the First n Elements of a Series

Using 'head()' method we can get 'n' number of rows from the dataset.

 

Example

head() : Get 5 rows from the beginning
head(n) : Get n rows from the beginning

 

head.py

import pandas as pd

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
series = pd.Series(primes)

print('Original Data : ')
print(series)

first_five_primes = series.head()
first_three_primes = series.head(3)

print('\nfirst_five_primes')
print(first_five_primes)

print('\nfirst_three_primes')
print(first_three_primes)

 

Output

Original Data : 
0      2
1      3
2      5
3      7
4     11
5     13
6     17
7     19
8     23
9     29
10    31
dtype: int64

first_five_primes
0     2
1     3
2     5
3     7
4    11
dtype: int64

first_three_primes
0    2
1    3
2    5
dtype: int64

‘head()’ method is a preview on original dataset, if you update something on the result returned by head() method, it updates the original data.



 

head_preview_update.py

import pandas as pd

primes = [2, 3, 5, 7]
series = pd.Series(primes)

print('Original Data : ')
print(series)

print('\nUpdating 1st prime to 11')
first_two_primes = series.head(2)
first_two_primes[0] = 11

print('\nAfter updating\n')
print(series)

Output

Original Data : 
0    2
1    3
2    5
3    7
dtype: int64

Updating 1st prime to 11

After updating

0    11
1     3
2     5
3     7
dtype: int64

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment