Pab*_*vas 8 python numpy scipy pandas
我试图从具有形状的数据框传递值到stats.friedmanchisquare.df(11,17)
这是什么样的工作,我(在这个例子中只为三排):
df = df.as_matrix()
print stats.friedmanchisquare(df[1, :], df[2, :], df[3, :])
Run Code Online (Sandbox Code Playgroud)
产量
(16.714285714285694, 0.00023471398805908193)
Run Code Online (Sandbox Code Playgroud)
但是,当我想要使用所有11行时, 代码行太长df.
首先,我尝试以下列方式传递值:
df = df.as_matrix()
print stats.friedmanchisquare([df[x, :] for x in np.arange(df.shape[0])])
Run Code Online (Sandbox Code Playgroud)
但我得到:
ValueError:
Less than 3 levels. Friedman test not appropriate.
Run Code Online (Sandbox Code Playgroud)
其次,我也尝试不将它转换为矩阵形式,将其作为DataFrame(这对我来说很理想),但我想这还不支持,或者我做错了:
print stats.friedmanchisquare([row for index, row in df.iterrows()])
Run Code Online (Sandbox Code Playgroud)
这也给了我错误:
ValueError:
Less than 3 levels. Friedman test not appropriate.
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是:基于参数传递给stats.friedmanchisquare的正确方法是什么df?(甚至使用其df.as_matrix()代表)
您可以在此处以csv格式下载我的数据帧并使用以下方式阅读:
df = pd.read_csv('df.csv', header=0, index_col=0)
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助 :)
基于@Ami Tavory和@ vicg的答案(请对它们进行投票),我的问题的解决方案,基于数据的矩阵表示,是添加这里定义的*-operator ,但在这里更好地解释,如下:
df = df.as_matrix()
print stats.friedmanchisquare(*[df[x, :] for x in np.arange(df.shape[0])])
Run Code Online (Sandbox Code Playgroud)
如果你想使用原始数据帧,这也是我理想的想法:
print stats.friedmanchisquare(*[row for index, row in df.iterrows()])
Run Code Online (Sandbox Code Playgroud)
以这种方式,您以原生格式迭代数据帧.
请注意,我说干就干,进行了一些timeit测试,看看哪种方式速度更快,事实证明,首先将其转换成一个numpy array事前预测快两倍,比使用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))
Run Code Online (Sandbox Code Playgroud)
产生以下结果:
4.97029900551
8.7627799511
Run Code Online (Sandbox Code Playgroud)
您可以使用“星号运算符”传递它,类似于:
a = np.array([[1, 2, 3], [2, 3, 4] ,[4, 5, 6]])
friedmanchisquare(*(a[i, :] for i in range(a.shape[0])))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1547 次 |
| 最近记录: |