Skip to content
Related Articles

Related Articles

Python | Pandas Series.add()
  • Last Updated : 01 Oct, 2018

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Python Series.add() is used to add series or list like objects with same length to the caller series.

Syntax: Series.add(other, level=None, fill_value=None, axis=0)

Parameters:
other: other series or list type to be added into caller series
fill_value: Value to be replaced by NaN in series/list before adding
level: integer value of level in case of multi index

Return type: Caller series with added values



To download the data set used in following example, click here.
In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.

Example #1: Adding List

In this example, the top 5 rows are stored in new variable using .head() method. After that a list of same length is created and added to the salary column using .add() method




# importing pandas module 
import pandas as pd
  
# reading csv file from url 
  
# creating short data of 5 rows
short_data = data.head()
  
# creating list with 5 values
list =[1, 2, 3, 4, 5]
  
# adding list data
# creating new column
short_data["Added values"]= short_data["Salary"].add(list)
  
# display
short_data


Output:
As shown in the output image, it can be compared that the Added value column is having the added values of Salary column + list.

 
Example #2: Adding series to series with null values

In this example, the Age column is added to the Salary column. Since the salary column contains null values too, by default it returns NaN no matter what is added. In this example, 5 is passed to replace null values with 5.




# importing pandas module 
import pandas as pd
  
# reading csv file from url 
  
# age series
age = data["Age"]
  
# na replacement
na = 5
  
# adding values
# storing to new column
data["Added values"]= data["Salary"].add(other = age, fill_value = na)
  
# display
data


Output:
As shown in the output image, the Added value column has added age column with 5 in case of Null values.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :