Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to select particular portion of column using row index range in Pandas DataFrame using python

for example: lets say we have a data frame named as students, where the column

index  name    value.  name
    0   a    0.469112  jai
    1   b   -0.282863  pria
    2   c   -1.509059  riya
    3   d   -1.135632  avantika 
    4   e    1.212112  Akashi
    5   f   -0.173215  conan
    6   g    0.119209  ai chan
    7   h   -1.044236  shinichi
    8   i   -0.861849  Edogawa
    9   j   -2.104569  black org

Now, I specifically want to select column values that are having rows in the range 4:8, i.e

4   e    1.212112  Akashi
5   f   -0.173215  conan
6   g    0.119209  ai chan
7   h   -1.044236  shinichi

I have just started understanding pandas, therefore I have doubt related to this stuff.

like image 616
codette Avatar asked Dec 04 '25 14:12

codette


2 Answers

Try using set_index and slicing:

>>> df.set_index('index')[4:8].reset_index()
   index name    value.    name.1
0      4    e  1.212112    Akashi
1      5    f -0.173215     conan
2      6    g  0.119209   ai chan
3      7    h -1.044236  shinichi
>>> 

Or try with conditioning:

>>> df[df['index'].lt(8) & df['index'].ge(4)]
   index name    value.    name.1
4      4    e  1.212112    Akashi
5      5    f -0.173215     conan
6      6    g  0.119209   ai chan
7      7    h -1.044236  shinichi
>>> 

Or just:

>>> df[4:8]
   index name    value.    name.1
4      4    e  1.212112    Akashi
5      5    f -0.173215     conan
6      6    g  0.119209   ai chan
7      7    h -1.044236  shinichi
>>> 
like image 104
U12-Forward Avatar answered Dec 07 '25 04:12

U12-Forward


You can use df.iloc[row_start:row_end, col_start:col_end] For your case, use the below code

students.iloc[4:8, :] # to take all columns we don't need to put any number range
like image 27
Foysal Khandakar Joy Avatar answered Dec 07 '25 03:12

Foysal Khandakar Joy