python - 对数据框列中的所有唯一值运行spicy.stats ANOVA 测试?
问题描述
我有一个数据框,其中包含许多城市及其相应的温度:
CurrentThermostatTemp
City
Cradley Heath 20.0
Cradley Heath 20.0
Cradley Heath 18.0
Cradley Heath 15.0
Cradley Heath 19.0
... ...
Walsall 16.0
Walsall 22.0
Walsall 20.0
Walsall 20.0
Walsall 20.0
[6249 rows x 1 columns]
唯一值是:
Index(['Cradley Heath', 'ROWLEY REGIS', 'Smethwick', 'Oldbury',
'West Bromwich', 'Bradford', 'Bournemouth', 'Poole', 'Wareham',
'Wimborne',
...
'St. Helens', 'Altrincham', 'Runcorn', 'Widnes', 'St Helens',
'Wakefield', 'Castleford', 'Pontefract', 'Walsall', 'Wednesbury'],
dtype='object', name='City', length=137)
我的目标是进行单向方差分析测试,即
from scipy.stats import f_oneway
对于数据框中的所有唯一值。也一样
SciPy.stats.f_oneway("all unique values")
并接收输出:所有变量的单向方差分析给出 {} with p-value {} 这是我尝试过很多次但不起作用的方法:
all = Tempvs.index.unique()
Tempvs.sort_index(inplace=True)
for n in range(len(all)):
truncated = Tempvs.truncate(all[n], all[n])
print(f_oneway(truncated))
解决方案
IIUC 你想要一个方差分析测试,其中每个样本都包含Temp
唯一元素的值City
。如果是这种情况,您可以这样做
import numpy as np
import pandas as pd
import scipy.stats as sps
# I create a sample dataset
index = ['Cradley Heath', 'ROWLEY REGIS',
'Smethwick', 'Oldbury',
'West Bromwich', 'Bradford',
'Bournemouth', 'Poole', 'Wareham',
'Wimborne','St. Helens', 'Altrincham',
'Runcorn', 'Widnes', 'St Helens',
'Wakefield', 'Castleford', 'Pontefract',
'Walsall', 'Wednesbury']
np.random.seed(1)
df = pd.DataFrame({
'City': np.random.choice(index, 500),
'Temp': np.random.uniform(15, 25, 500)
})
# populate a list with all
# values of unique Cities
values = []
for city in df.City.unique():
_df = df[df.City==city]
values.append(_df.Temp.values)
# compute the ANOVA
# with starred *list
# as arguments
sps.f_oneway(*values)
在这种情况下,将给出
F_onewayResult(statistic=0.4513685152123563, pvalue=0.9788508507035195)
PS:不要
all
用作变量,因为它是一个内置的python函数,见https://docs.python.org/3/library/functions.html#all
推荐阅读
- java - 如何在 JOOQ 中仅从日期时间中提取日期部分
- angular - 将刷新和仪表板命令传递给其他模块
- lua - 如何在Garry的mod lua服务器中将图像放置在播放器的屏幕上
- mathjax - 使用 MathJax v3.0 的自动方程编号
- php - 如何获得 Carbon/Carbon 的住宿天数?
- css - 使用样式组件更改 Ant Design 中标题组件的颜色?
- css - clip-path svg 适用于图像,但不适用于 div
- python-3.x - 覆盖字典__getitem__魔术方法时出现递归错误?
- ios - 如何在你的 Flutter 应用中创建 Runner.xcworkspace?
- javascript - 在 nuxt.js 页面中包含外部 javascript 文件