Question: How do I change this R code to Python? import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns

How do I change this R code to Python?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from statsmodels.api import OLS
# Assuming data loading and creation is done similarly
# Example: Importing data using pandas
# Replace `"C:/Users/slaug/Downloads/MIS470GDP.xls"` with the actual path to your Excel file
MIS470GDP = pd.read_excel("C:/Users/slaug/Downloads/MIS470GDP.xls")
# Generate random data for the example as in original R code
np.random.seed(123)
n =100
GDP = np.random.uniform(10000,100000, n)
true_intercept =5000
true_slope =0.1
noise = np.random.normal(0,3000, n)
USEUR = true_intercept + true_slope * GDP + noise
# Create a DataFrame
data = pd.DataFrame({'GDP': GDP, 'USEUR': USEUR})
# View the first few rows of the data
print(data.head())
# Scatter plot of GDP vs. USEUR
plt.figure(figsize=(10,6))
sns.scatterplot(data=data, x='GDP', y='USEUR')
plt.title("Scatter Plot of GDP vs. USEUR")
plt.xlabel('GDP')
plt.ylabel('USEUR')
plt.show()
# Fit the linear regression model
X = data['GDP']
y = data['USEUR']
X = np.add_constant(X) # adding a constant for intercept
model = OLS(y, X).fit()
# Summary of the model
print(model.summary())
# Predict USEUR for a new GDP value
new_data = pd.DataFrame({'GDP': [22007.372]})
new_data = np.add_constant(new_data) # adding a constant for intercept
predicted_USEUR = model.predict(new_data)
print(f'Predicted USEUR for GDP =22007.372 is {predicted_USEUR[0]}')
# Create the scatter plot with regression line
plt.figure(figsize=(10,6))
sns.scatterplot(data=data, x='GDP', y='USEUR')
sns.lineplot(x='GDP', y=model.fittedvalues, data=data, color='blue', label='Fitted line')
plt.title("Scatter Plot with Linear Regression Line")
plt.xlabel('GDP')
plt.ylabel('USEUR')
plt.show()
# 90% Confidence Interval
confidence_level =0.90
degrees_freedom = len(data)-2
confidence_interval = stats.t.interval(confidence_level, degrees_freedom, loc=model.params[1], scale=model.bse[1])
print(f"90% Confidence Interval: [{round(confidence_interval[0],2)},{round(confidence_interval[1],2)}]")

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!