2016-07-26 55 views
3

我具有基於不同氣象站幾個變量(溫度,壓力等)的數據集,Python的熊貓 - 構造多元樞軸表來顯示NaN和非NaN的

stationID | Time | Temperature | Pressure |... 
----------+------+-------------+----------+ 
123  | 1 |  30  | 1010.5 | 
123  | 2 |  31  | 1009.0 | 
202  | 1 |  24  | NaN  | 
202  | 2 |  24.3 | NaN  | 
202  | 3 |  NaN  | 1000.3 | 
... 

和我想的計數想創建一個數據透視表,將顯示NaN,並且每氣象站非NaN的,這樣的數字:

stationID | nanStatus | Temperature | Pressure |... 
----------+-----------+-------------+----------+ 
123  | NaN  |  0  |  0 |  
      | nonNaN |  2  |  2 | 
202  | NaN  |  1  |  2 | 
      | nonNaN |  2  |  1 | 
... 

下面我展示一下我迄今所做的,它的工作原理(以繁瑣的方式)的溫度。但是,如何獲得兩個變量的相同,如上所示?

import pandas as pd 
import bumpy as np 
df = pd.DataFrame({'stationID':[123,123,202,202,202], 'Time':[1,2,1,2,3],'Temperature':[30,31,24,24.3,np.nan],'Pressure':[1010.5,1009.0,np.nan,np.nan,1000.3]}) 

dfnull = df.isnull() 
dfnull['stationID'] = df['stationID'] 
dfnull['tempValue'] = df['Temperature'] 
dfnull.pivot_table(values=["tempValue"], index=["stationID","Temperature"], aggfunc=len,fill_value=0) 

輸出是:

---------------------------------- 
         tempValue 
stationID | Temperature   
123  | False    2 
202  | False    2 
      | True     1 

回答

3

UPDATE:感謝@root

In [16]: df.groupby('stationID')[['Temperature','Pressure']].agg([nans, notnans]).astype(int).stack(level=1) 
Out[16]: 
        Temperature Pressure 
stationID 
123  nans    0   0 
      notnans   2   2 
202  nans    1   2 
      notnans   2   1 

原來的答覆:

In [12]: %paste 
def nans(s): 
    return s.isnull().sum() 

def notnans(s): 
    return s.notnull().sum() 
## -- End pasted text -- 

In [37]: df.groupby('stationID')[['Temperature','Pressure']].agg([nans, notnans]).astype(np.int8) 
Out[37]: 
      Temperature   Pressure 
       nans notnans  nans notnans 
stationID 
123     0  2  0  2 
202     1  2  2  1 
+2

您可以用'.STACK完成它(等級= 1)' – root

+0

@root,是的,就是這樣,非常感謝很多! – MaxU

+0

真棒,@MaxU和@root! '.stack(level = 1)'是蛋糕上的糖霜! (我只是希望有一種方法可以將輸出四捨五入到最接近的整數。我曾嘗試使用'round'和'int',但它們不起作用) – mmeclimate

0

我承認這不是最漂亮的解決方案,但它有效。首先定義兩個臨時列TempNaNPresNaN

df['TempNaN'] = df['Temperature'].apply(lambda x: 'NaN' if x!=x else 'NonNaN') 
df['PresNaN'] = df['Pressure'].apply(lambda x: 'NaN' if x!=x else 'NonNaN') 

然後定義使用多指標的結果數據框:

Results['Temperature'] = df.groupby(['stationID','TempNaN'])['Temperature'].apply(lambda x: x.shape[0]) 
Results['Pressure'] = df.groupby(['stationID','PresNaN'])['Pressure'].apply(lambda x: x.shape[0]) 

,並填補了:

Results = pd.DataFrame(index=pd.MultiIndex.from_tuples(list(zip(*[sorted(list(df['stationID'].unique())*2),['NaN','NonNaN']*df['stationID'].nunique()])),names=['stationID','NaNStatus'])) 

Store中的結果數據框計算零值空白值:

Results.fillna(value=0,inplace=True) 

如果更容易,您可以遍歷列。例如:

Results = pd.DataFrame(index=pd.MultiIndex.from_tuples(list(zip(*[sorted(list(df['stationID'].unique())*2),['NaN','NonNaN']*df['stationID'].nunique()])),names=['stationID','NaNStatus'])) 
for col in ['Temperature','Pressure']: 
    df[col + 'NaN'] = df[col].apply(lambda x: 'NaN' if x!=x else 'NonNaN') 
    Results[col] = df.groupby(['stationID',col + 'NaN'])[col].apply(lambda x: x.shape[0]) 
    df.drop([col + 'NaN'],axis=1,inplace=True) 
Results.fillna(value=0,inplace=True) 
0
d = {'stationID':[], 'nanStatus':[], 'Temperature':[], 'Pressure':[]} 

for station_id, data in df.groupby(['stationID']): 

    temp_nans = data.isnull().Temperature.mean()*data.isnull().Temperature.count() 
    pres_nans = data.isnull().Pressure.mean()*data.isnull().Pressure.count() 

    d['stationID'].append(station_id) 
    d['nanStatus'].append('NaN') 
    d['Temperature'].append(temp_nans) 
    d['Pressure'].append(pres_nans) 

    d['stationID'].append(station_id) 
    d['nanStatus'].append('nonNaN') 
    d['Temperature'].append(data.isnull().Temperature.count() - temp_nans) 
    d['Pressure'].append(data.isnull().Pressure.count() - pres_nans) 

df2 = pd.DataFrame.from_dict(d) 
print(df2) 

結果是:

Pressure Temperature nanStatus stationID 
0  0.0   0.0  NaN  123 
1  2.0   2.0 nonNaN  123 
2  2.0   1.0  NaN  202 
3  1.0   2.0 nonNaN  202