2017-03-06 124 views
1

迭代組給定的數據幀如下:熊貓:由對象

In [8]: 
df 
Out[8]: 
Experiment SampleVol Mass 
0 A 1 11 
1 A 1 12 
2 A 2 20 
3 A 2 17 
4 A 2 21 
5 A 3 28 
6 A 3 29 
7 A 4 35 
8 A 4 38 
9 A 4 35 
10 B 1 12 
11 B 1 11 
12 B 2 22 
13 B 2 24 
14 B 3 30 
15 B 3 33 
16 B 4 37 
17 B 4 42 
18 C 1 8 
19 C 1 7 
20 C 2 17 
21 C 2 19 
22 C 3 29 
23 C 3 30 
24 C 3 31 
25 C 4 41 
26 C 4 44 
27 C 4 42 

我想處理每個實驗的數據幀一定的相關性研究。我想要進行的研究是計算'SampleVol'與其平均值('質量')的相關性。

groupby函數可以幫助我得到羣衆的意思。 grp = df.groupby(['Experiment', 'SampleVol']) grp.mean()

Out[17]: 
         Mass 
Experiment SampleVol 
A   1   11.500000 
      2   19.333333 
      3   28.500000 
      4   36.000000 
B   1   11.500000 
      2   23.000000 
      3   31.500000 
      4   39.500000 
C   1   7.500000 
      2   18.000000 
      3   30.000000 
      4   42.333333 

我理解爲每個數據幀應該使用一些numpy的函數來計算的相關係數。但現在,我的問題是我如何迭代每個實驗的數據幀。

以下是所需輸出的示例。

Out[18]: 

Experiment Slope Intercept 
A   0.91 0.01 
B   1.1 0.02 
C   0.95 0.03 

非常感謝。

+0

如果迭代是你的目標,你可以簡單地爲標籤做',排在df.iterrows()'。 – spicypumpkin

+2

你可以發佈所需的輸出嗎? –

+0

@ JoeT.Boka我編輯所需輸出的帖子。 –

回答

0

您只需在「實驗」列上進行分組,而不是像上面那樣對兩列進行分組。您可以通過組進行迭代,並使用下面的代碼在分組值進行簡單線性迴歸:

from scipy import stats 
import pandas as pd 
import numpy as np 

grp = df.groupby(['Experiment']) 

output = pd.DataFrame(columns=['Slope', 'Intercept']) 

for name, group in grp: 
    slope, intercept, r_value, p_value, std_err = stats.linregress(group['SampleVol'], group['Mass']) 
    output.loc[name] = [slope,intercept] 

print(output) 

enter image description here

對於那些好奇的,我這是怎麼產生的無效數據,它是什麼樣子:

df = pd.DataFrame() 
df['Experiment'] = np.array(pd.date_range('2018-01-01', periods=12, freq='6h').strftime('%a')) 
df['SampleVol'] = np.random.uniform(1,5,12) 
df['Mass'] = np.random.uniform(10,42,12) 

enter image description here

參考文獻: