私はDataFrame
ですが、各行は交通事故を表しています。列のうちの2つはSpeed_limit
とNumber_of_casualties
です。私はスピードリミットと各スピードリミットの事故に対する死傷者数の比のピアソン相関係数を計算したいと思います。パンダでグループ分けされた量の相関係数を計算するには?
私のソリューション配列として、関連量を取得し、scipyのダウンロードのpearsonr
を使用することです:
import pandas as pd
import scipy.stats
df = pd.DataFrame({'Speed_limit': [10, 10, 20, 20, 20, 30],
'Number_of_casualties': [1, 2, 3, 4, 1, 4]})
accidents_per_speed_limit = df['Speed_limit'].value_counts().sort_index()
number_of_casualties_per_speed_limit = df.groupby('Speed_limit').sum()['Number_of_casualties']
speed_limit = accidents_per_speed_limit.index
ratio = number_of_casualties_per_speed_limit.values/accidents_per_speed_limit.values
r, _ = scipy.stats.pearsonr(x=speed_limit, y=ratio)
print("The Pearson's correlation coefficient between the number of casualties per accidents and the speed limit is {r}.".format(r=r))
しかし、pandas.DataFrame.corrメソッドを使用して、よりエレガントにこれを行うことが可能であるべきであるように私には思われます。どのようにしてこのコードをリファクタリングして、それをもっとpandas
のようにすることができますか?
代わりに、カウントと合計私たちの直接平均を使用することができます。 – Dark