你好,
我正在尝试开发一个函数,它将两个表达式作为输入:平台名称(例如,"PS2")和评论类型(例如,“评论家评分”)。
函数的目标是确定平台的总体销量与排名类型(“评论家评分”)之间的关联:
def corfunc(Platform, score_type):
df5 = df_new[(df_new.platform==Platform)&(df_new[score_type].notna())][['total_sales',score_type]]
df5.plot(x=score_type, y='total_sales', kind='hexbin', gridsize=20, sharex=False, alpha=1)
correlation=df5.corr(method='pearson')
if [[correlation > 0.7]]:
result=print(correlation)
print('There is a strong positive connection')
elif [[correlation < -0.7]]:
print('There is a strong negative connection')
else:
result=print('No/weak connection')
print(result)这里是一个已经过滤的数据示例:
pita=df_new[(df_new.platform=='PS3')&(df_new['critic_score'].notna())][['total_sales','critic_score']]pita.head(3)
total_sales critic_score
16 21.05 97.0
34 13.79 83.0
37 13.33 88.0--我希望能对if/ into语句的结果提供一些语法上的帮助:,当我检查函数输出时,它似乎没有考虑到相关的分数,似乎存在着完全和正相关的关系。我希望我的函数考虑多重相关性,而不仅仅是检查变量本身的相关性。谢谢!
corfunc('PS3', 'critic_score') total_sales critic_score
total_sales 1.000000 0.379961
critic_score 0.379961 1.000000
There is a strong positive connection
None发布于 2022-07-13 10:51:37
若要获取一个变量与另一个变量之间的相关性,请使用Series.corr
correlation = df["critic_score"].corr(df["total_sales"])如前所述,变量与自身的相关性始终是1。
当前代码中出现问题的原因是返回数据文件。df.corr() > .7不返回单个True/False值,而是返回另一个dataframe,如果原始dataframe > .7中的每个值都包含True,则返回False。
因此,df.corr() > 7不能用作if语句中的条件。您需要在dataframe中选择一个值,或者使用(correlation > .7).any(axis=None)来检查其中任何一个值是否高于.7。(将dataframe放在方括号中可以防止引发错误,但不会做任何有用的事情。)但这两个系列之间的相关性更容易计算,如上面所示。
发布于 2022-07-13 10:38:38
与其本身的相关性总是1.0,因为它遵循的是完全相同的数据。就像你的例子
total_sales critic_score
total_sales 1.000000 0.379961
critic_score 0.379961 1.000000total_sales与critic_score之间的相关系数为0.379,而相对于自身而言,两者之间的相关关系并不是很有趣。
让它更加直观的一种方法是使用热图来可视化关联,而不是仅仅看纯数字。
我经常使用海运热图,它可以使用这样的DF:
import seaborn as sns
# With annotation true you get the values within the squares
sns.heatmap(dataframe, anoot=True)要将正确的成对功能与句子结合起来,应该是这样的(就像斯图尔特提到的那样):
def corfunc(Platform, score_type):
df5 = df_new[(df_new.platform==Platform)&(df_new[score_type].notna())][['total_sales',score_type]]
df5.plot(x=score_type, y='total_sales', kind='hexbin', gridsize=20, sharex=False, alpha=1)
correlation = df5["critic_score"].corr(df["total_sales"], method='pearson')
if correlation > 0.7:
result=print(correlation)
print('There is a strong positive connection')
elif correlation < -0.7:
print('There is a strong negative connection')
else:
result=print('No/weak connection')
print(result)https://stackoverflow.com/questions/72964647
复制相似问题