CBSE CS and IP

CBSE Class 11 & 12 Computer Science and Informatics Practices Python Materials, Video Lecture

Modifying Pandas Series Elements

pandas series modifying the elements

If you know how to extract the series single element and Series slice, it is very simple for you to change the series elements. You can change a single element or a full slice of the series object.

Whatever you want to change in a series you have to access that element and assign it with the new value. 

Consider the following Series Object:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    import pandas as pd
    student = pd.Series(
    data = ["BOB", "JHON", "RAM", "MOHAN"],
    index = ['S1','S2','S3','S4'])
    print(student)
    
    '''
    S1      BOB
    S2     JHON
    S3      RAM
    S4    MOHAN
    dtype: object
    '''
    


    Following are the different types, using which you can modify the elements of a series object.

  1. <series object> [<index>] = <new data value>
    To assign a new value you have to simply access the value using the Series label or index position as described below. Then you have to just provide the new value by giving the assignment operator.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    student['S1'] = "JACK"
    student[2] = "PETER"
    print(student)
    
    '''
    S1     JACK
    S2     JHON
    S3    PETER
    S4    MOHAN
    dtype: object
    '''
    

  2. <series object> [start : stop] = <new data value>
    If you want to change a slice of values, you can provide the values using the colon (:), after that you can provide a scalar value or the value in the form of a list.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    student['S3':'S4'] = "JACK"
    student[0:1] = "PETER"
    print(student)
    
    '''
    S1    PETER
    S2     JHON
    S3     JACK
    S4     JACK
    dtype: object
    '''
    

  3. loc and iloc attribute
    You can use loc or iloc to modify the existing values in the series. In both the cases you have to provide the new value using assignment operator.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    student.loc['S3'] = "JACK"
    student.iloc[3] = "PETER"
    print(student)
    '''
    S1      BOB
    S2     JHON
    S3     JACK
    S4    PETER
    
    dtype: object
    '''
    


For more clarification you can watch the follwing video lecture on this topic:



No comments:

Post a Comment