Python 基于数据帧向stats.friedmanchisquare传递参数的正确方法是什么?

Python 基于数据帧向stats.friedmanchisquare传递参数的正确方法是什么?,python,numpy,pandas,scipy,Python,Numpy,Pandas,Scipy,我试图将值从数据帧df传递到,该数据帧具有形状(11,17) 这就是对我有效的方法(本例中仅适用于三行): 产生 (16.714285714285694, 0.00023471398805908193) 但是,当我想使用df的所有11行时,代码行太长 首先,我尝试以以下方式传递值: df = df.as_matrix() print stats.friedmanchisquare([df[x, :] for x in np.arange(df.shape[0])]) 但我得到: ValueE

我试图将值从数据帧
df
传递到,该数据帧具有形状
(11,17)

这就是对我有效的方法(本例中仅适用于三行):

产生

(16.714285714285694, 0.00023471398805908193)
但是,当我想使用
df
的所有
11
行时,代码行太长

首先,我尝试以以下方式传递值:

df = df.as_matrix()
print stats.friedmanchisquare([df[x, :] for x in np.arange(df.shape[0])])
但我得到:

ValueError: 
Less than 3 levels.  Friedman test not appropriate.
其次,我也尝试过不将其转换为矩阵形式,而将其作为数据帧(这对我来说非常理想),但我想这还不受支持,或者我做错了:

print stats.friedmanchisquare([row for index, row in df.iterrows()])
这也给了我一个错误:

ValueError: 
Less than 3 levels.  Friedman test not appropriate.
因此,我的问题是:基于
df
传递参数的正确方法是什么?(甚至使用其
df.as_matrix()
表示法)

您可以下载csv格式的“我的数据帧”,并使用以下方式读取:

df = pd.read_csv('df.csv', header=0, index_col=0)
谢谢你的帮助:)

解决方案: 根据@Ami Tavory和@vicg的答案(请投票表决),根据数据的矩阵表示,我的问题的解决方案是添加
*
-运算符,但如下所示:

df = df.as_matrix()
print stats.friedmanchisquare(*[df[x, :] for x in np.arange(df.shape[0])])
如果您想使用原始数据帧,也同样如此,这正是我理想中想要的:

print stats.friedmanchisquare(*[row for index, row in df.iterrows()])
通过这种方式,您可以在数据帧上以其本机格式进行迭代

注意我继续运行了一些
timeit
测试,以查看哪种方法更快,结果表明,先将其转换为
numpy数组
比使用原始数据帧格式的
df
快一倍

这是我的实验装置:

import timeit

setup = '''
import pandas as pd
import scipy.stats as stats
import numpy as np
df = pd.read_csv('df.csv', header=0, index_col=0)
'''

theCommand = '''
df = np.array(df)
stats.friedmanchisquare(*[df[x, :] for x in np.arange(df.shape[0])])
'''

print min(timeit.Timer(stmt=theCommand, setup=setup).repeat(10, 10000))

theCommand = '''
stats.friedmanchisquare(*[row for index, row in df.iterrows()])
'''

print min(timeit.Timer(stmt=theCommand, setup=setup).repeat(10, 10000))
这将产生以下结果:

4.97029900551
8.7627799511

我在第一次尝试中看到的问题是,您最终会传递一个列表,其中包含多个数据帧

stats.friedmanchisquare需要多个类似数组的参数,而不是一个列表

尝试使用操作员打开列表

像这样

df = df.as_matrix()
print stats.friedmanchisquare(*[df[x, :] for x in np.arange(df.shape[0])])

您可以使用传递它,类似于:

a = np.array([[1, 2, 3], [2, 3, 4] ,[4, 5, 6]])
friedmanchisquare(*(a[i, :] for i in range(a.shape[0])))
a = np.array([[1, 2, 3], [2, 3, 4] ,[4, 5, 6]])
friedmanchisquare(*(a[i, :] for i in range(a.shape[0])))