我有 4 个变量,其中 2 个是名义变量(dtype=object),2 个是数字变量(dtypes=int 和 float)。
df.head(1)
OUT:
OS_type|Week_day|clicks|avg_app_speed
iOS|Monday|400|3.4
现在,我想将数据框放入 seaborn 热图可视化中。
import numpy as np
import seaborn as sns
ax = sns.heatmap(df)
但我收到一条错误消息,指出我不能使用分类变量,只能使用数字。我如何正确处理它然后将其反馈到热图中?
最佳答案
要绘制的热图需要介于 0 和 1 之间的值。对于数值变量之间的相关性,您可以使用 Pearson's R,对于分类变量(校正后的)Cramer's V,对于分类变量和数值变量之间的相关性,您可以使用相关率.
至于创建分类变量的数字表示,有多种方法可以做到这一点:
import pandas as pd
from sklearn.preprocessing import LabelEncoder
df = pd.read_csv('some_source.csv') # has categorical var 'categ_var'
# method 1: uses pandas
df['numerized1'] = df['categ_var'].astype('category').cat.codes
# method 2: uses pandas, sorts values descending by frequency
df['numerized2'] = df['categ_var'].apply(lambda x: df['categ_var'].value_counts().index.get_loc(x))
# method 3: uses sklearn, result is the same as method 1
lbl = LabelEncoder()
df['numerized3'] = lbl.fit_transform(df['categ_var'])
# method 4: uses pandas; xyz captures a list of the unique values
df['numerized4'], xyz = pd.factorize(df['categ_var'])
https://stackoverflow.com/questions/57280472/
相关文章:
javascript - 在 Angular 2+ 上重新渲染 FullCalendar
firebase - oobCodes 在 Firebase 中的生命周期
spring - 让 Spring RestTemplate 使用内存中的 pem 证书(不在磁盘上
flutter - flutter 的 video_playeur 包问题
django - 自定义 Django Admin 用户密码修改表单
spring-boot - Spring Boot - Rest Controller 响应两个 J
asp.net-core-2.0 - 如何在 .net 核心 web api 中将 Razor Vi