3 回答

TA貢獻1815條經驗 獲得超6個贊
from scipy.stats import pearsonr
df_full = df1.merge(df2,how='left')
full_correlation = pearsonr(df_full['BSL'],df_full['Accidents'])
print('Correlation coefficient:',full_correlation[0])
print('P-value:',full_correlation[1])
輸出:
(-0.2934597230564072, 0.3811116115819819)
Correlation coefficient: -0.2934597230564072
P-value: 0.3811116115819819
編輯:
您想要每小時的相關性,但在數學上這是不可能的,因為您每小時只有 1 個 xy 值。因此,輸出將充滿 NaN。這是代碼,但是輸出無效:
df_corr = df_full.groupby('Datetime')['BSL','Accidents'].corr().drop(columns='BSL').drop('Accidents',level=1).rename(columns={'Accidents':'Correlation'})
print(df_corr)
輸出:
Correlation
Datetime
7 BSL NaN
8 BSL NaN
9 BSL NaN
10 BSL NaN
11 BSL NaN
12 BSL NaN
13 BSL NaN
14 BSL NaN
15 BSL NaN
16 BSL NaN
17 BSL NaN

TA貢獻1818條經驗 獲得超3個贊
由于您的數據框有多個列,因此您需要指定要使用的列的名稱:
df1['BSL'].corr(df2['Number of Accident'], "pearson")

TA貢獻1765條經驗 獲得超5個贊
corr()pandas 數據幀的方法計算一個數據幀中所有列的相關矩陣。您有兩個數據框,因此該方法不起作用。您可以通過以下方式解決此問題:
df1['number'] = df2['Number of Accident']
df1.corr("pearson")
添加回答
舉報