Python | Pandas Series.corr ()

Python Methods and Functions

Series.corr() Pandas Series.corr() calculates correlation with others Series.corr () , excluding missing values.

Syntax: Series.corr (other, method = 'pearson' , min_periods = None)

Parameter:
other: Series
method: {' pearson ',' kendall ',' spearman '} or callable
min_periods: Minimum number of observations needed to have a valid result

Returns: correlation: float

Example # 1: Use Series.corr () to find the correlation of a given series object with another.

# import pandas as pd

import pandas as pd

  
# Create the first episode

sr1 = pd.Series ([ 80 , 25 , 3 , 25 , 24 , 6 ])

 
# Create second episode

sr2 = pd.Series ([ 34 , 5 , 13 , 32 , < code class = "value"> 4 , 15 ])

 
# Create Index

index_ = [ 'Coca Cola' , 'Sprite' , ' Coke' , 'Fanta' , 'Dew' , ' ThumbsUp' ]

 
# set first index

sr1.index = index_

 
 # set the second index

sr2.index = index_

 
# Print first episode

print (sr1)

  
# Print the second series

print ( sr2)

Output:

We will now use Series.corr () to find the correlation between the master data of this series object and others.

# find correlation

result = sr1.corr (sr2)

  
# Print result

print (result)

Output:

As we can see from the output, Series.corr () successfully returned the correlation between the underlying data of the objects in this series.

Example # 2 : Use Series.corr () to find the correlation of a given series object with another. The series object contains some missing values.

# import pandas as pd

import pandas as pd

 
# Create first episode

sr1 = pd.Series ([ 51 , 10 , 24 , 18 , None , 84 , 12 , 10 , 5 , 24 , 2 ])

 
# Create the second episode

sr2 = pd .Series ([ 11 , 21 , 8 , 18 , 65 , 18 , 32 , 10 , 5 , 32 , None ])

 
# Create Index

index_ = pd.date_range ( '2010 -10-09' , periods = 11 , freq = 'M' )

 
# set first index

sr1.index = index_

 
# set second index

sr2.index = index_

 
# Printout Attach first series

print (sr1)

 
# Print the second batch

print (sr2)

Output:

We will now use Series.corr () to find the correlation between the master data of a given series object and others.

# find correlation

result = sr1.corr (sr2)

 
# Print result

print (result)

Output:

As we can see from the output, Series.corr () successfully returned a correlation between the underlying data of the objects in this series. Missing values ​​are ignored when calculating the correlation between objects.





Get Solution for free from DataCamp guru