2016-08-24 70 views
2

我需要計算2D網格的每個節點的統計信息。我認爲簡單的做法是採用兩個範圍的交叉連接(AKA笛卡爾積)。numpy數組轉換爲熊貓數據框丟棄值

def node_grid(x_range, y_range, x_increment, y_increment): 
    x_min = float(x_range[0]) 
    x_max = float(x_range[1]) 
    x_num = (x_max - x_min)/x_increment + 1 
    y_min = float(y_range[0]) 
    y_max = float(y_range[1]) 
    y_num = (y_max - y_min)/y_increment + 1 

    x = np.linspace(x_min, x_max, x_num) 
    y = np.linspace(y_min, y_max, y_num) 

    ng = list(product(x, y)) 
    ng = np.array(ng) 
    return ng, x, y 

然而,當我將它轉換爲一個pandas數據幀將丟棄值:我用這個作爲numpy此功能實現。例如:

In [2]: ng = node_grid(x_range=(-60, 120), y_range=(0, 40), x_increment=0.1, y_increment=0.1) 
In [3]: ng[0][(ng[0][:,0] > -31) & (ng[0][:,0] < -30) & (ng[0][:,1]==10)] 
Out[3]: array([[-30.9, 10. ], 
    [-30.8, 10. ], 
    [-30.7, 10. ], 
    [-30.6, 10. ], 
    [-30.5, 10. ], 
    [-30.4, 10. ], 
    [-30.3, 10. ], 
    [-30.2, 10. ], 
    [-30.1, 10. ]]) 

In [4]: node_df = pd.DataFrame(ng[0]) 
node_df.columns = ['xx','depth'] 
print(node_df[(node_df.depth==10) & node_df.xx.between(-30,-31)]) 
Out[4]:Empty DataFrame 
Columns: [xx, depth] 
Index: [] 

的數據幀不是空的:從numpy的陣列

In [5]: print(node_df.head()) 
Out[5]:  xx depth 
0 -60.0 0.0 
1 -60.0 0.1 
2 -60.0 0.2 
3 -60.0 0.3 
4 -60.0 0.4 

值時,它們被放入大熊貓陣列被丟棄。爲什麼?

+0

能否請您指定要使用'product'功能。發佈代碼不適合我。 – Ascurion

回答

1

的「之間」的功能要求,第一個參數小於後者。

In: print(node_df[(node_df.depth==10) & node_df.xx.between(-31,-30)]) xx depth 116390 -31.0 10.0 116791 -30.9 10.0 117192 -30.8 10.0 117593 -30.7 10.0 117994 -30.6 10.0 118395 -30.5 10.0 118796 -30.4 10.0 119197 -30.3 10.0 119598 -30.2 10.0 119999 -30.1 10.0 120400 -30.0 10.0

爲了清楚起見使用了product()功能來自itertools包,即from itertools import product

0

我無法完全重現您的代碼。

但我發現問題是,你必須在between查詢中圍繞下限和上限。對我來說,以下工作:

print(node_df[(node_df.depth==10) & node_df.xx.between(-31,-30)]) 

時使用:

ng = np.array([[-30.9, 10. ], 
       [-30.8, 10. ], 
       [-30.7, 10. ], 
       [-30.6, 10. ], 
       [-30.5, 10. ], 
       [-30.4, 10. ], 
       [-30.3, 10. ], 
       [-30.2, 10. ], 
       [-30.1, 10. ]]) 
node_df = pd.DataFrame(ng) 
相關問題