find a correlation between two variables in python

To find the correlation between two variables in Python, we can utilize the corr() method from the Pandas library. Here's an example code:

main.py
import pandas as pd

# create a dataframe with two columns
data = {'x': [1, 2, 3, 4, 5], 'y': [10, 20, 15, 25, 30]}
df = pd.DataFrame(data)

# calculate the correlation between the two variables
corr = df['x'].corr(df['y'])

# print the correlation
print("Correlation between x and y:", corr)
293 chars
12 lines

The corr() method takes in two variables and returns the correlation coefficient between them. The correlation coefficient can range between -1 and 1, where a value of -1 indicates a perfect negative correlation, 0 indicates no correlation, and 1 indicates a perfect positive correlation.

related categories

gistlibby LogSnag