我想根据字符串列的值计数创建一个相关矩阵。因此,这里有事故严重性和时间。 我试图显示一天中的时间与事故严重程度之间的相关性
Pandas数据框(df)的一部分:
+-----------------------+-------------------+------------------+
| Accident_Index | Time | Accident_Severity|
+-----------------------+-------------------+------------------+
| 200501BS00001 | Morning | Serious |
| 200501BS00002 | Night | Slight |
| 200501BS00003 | Evening | Slight |
| 200501BS00004 | Afternoon | Fatal |
+-----------------------+-------------------+------------------+
我的预期输出是这样的:
+---------+-----------+-------+---------+-----------+
| | Morning | Night | Evening | Afternoon |
+---------+-----------+-------+---------+-----------+
| Serious | 0.9 | 0.3 | 0.3 | 0.3 |
| Slight | 0.8 | 1 | 0.2 | 0.5 |
| Fatal | 0.4 | 0.3 | 1 | 0.3 |
+---------+-----------+-------+---------+-----------+
我已经尝试过这种事情:
s_corr = df.Accident_Severity.str.get_dummies(' ').corrwith(df.Time.value_counts() / df.Time.value_counts().max())
print(s_corr)
输出:
这:
corrs = df.pivot('Time','Accident_Severity').T.corr().stack()
corrs.index.names = 'Time', 'Accident_Severity'
corrs.reset_index()
print(corrs)
输出:
这:
corrs = df.reset_index().pivot_table('Time','Accident_Severity').T.corr().stack()
print(corrs)
输出:
这:
acc = df['Accident_Severity'].value_counts()
ti = df['Time'].value_counts()
print(acc.corr(ti))
输出:
答案 0 :(得分:1)
我不太了解这里的预期输出。但是给出一些数据:
import random
severity_choices = ['Slight', 'Serious', 'Fatal']
time_choices = ['Morning', 'Afternoon', 'Evening', 'Night']
df = pd.DataFrame({
'Severity': [random.choice(severity_choices) for i in range(0, 1000)],
'Time': [random.choice(time_choices) for i in range(0, 1000)]
})
我们可以使用设置为Severity
的{{3}}和normalize
来计算每个index
的比例。
>> pd.crosstab(df['Severity'], df['Time'], normalize='index')
Time Afternoon Evening Morning Night
Severity
Fatal 0.246106 0.249221 0.224299 0.280374
Serious 0.253125 0.234375 0.253125 0.259375
Slight 0.233983 0.233983 0.267409 0.264624