簡體   English   中英

熊貓將功能列表應用於數據框

[英]pandas apply list of function to data frame

讓我們from sklearn.datasets import load_boston獲取可用的波士頓數據集

boston = load_boston()
X = pd.DataFrame(boston["data"])

           0     1      2    3      4      5      6       7     8      9     10      11     12
0     0.00632  18.0   2.31  0.0  0.538  6.575   65.2  4.0900   1.0  296.0  15.3  396.90   4.98
1     0.02731   0.0   7.07  0.0  0.469  6.421   78.9  4.9671   2.0  242.0  17.8  396.90   9.14
2     0.02729   0.0   7.07  0.0  0.469  7.185   61.1  4.9671   2.0  242.0  17.8  392.83   4.03
3     0.03237   0.0   2.18  0.0  0.458  6.998   45.8  6.0622   3.0  222.0  18.7  394.63   2.94
4     0.06905   0.0   2.18  0.0  0.458  7.147   54.2  6.0622   3.0  222.0  18.7  396.90   5.33
5     0.02985   0.0   2.18  0.0  0.458  6.430   58.7  6.0622   3.0  222.0  18.7  394.12   5.21
6     0.08829  12.5   7.87  0.0  0.524  6.012   66.6  5.5605   5.0  311.0  15.2  395.60  12.43

我建立了機器學習模型(RF),並獲得了模型中的所有估計量。

estimators = model.estimators_

您可以認為這具有獲取行級數據並返回值的函數列表。

>> estimators = model.estimators_
>> estimators
[DecisionTreeRegressor(criterion='mse', max_depth=60, max_features=8,
           max_leaf_nodes=None, min_impurity_decrease=0.0,
           min_impurity_split=None, min_samples_leaf=5,
           min_samples_split=12, min_weight_fraction_leaf=0.0,
           presort=False, random_state=1838148368, splitter='best'), DecisionTreeRegressor(criterion='mse', max_depth=60, max_features=8,
           max_leaf_nodes=None, min_impurity_decrease=0.0,
           min_impurity_split=None, min_samples_leaf=5,
           min_samples_split=12, min_weight_fraction_leaf=0.0,
           presort=False, random_state=1754873550, splitter='best'), DecisionTreeRegressor(criterion='mse', max_depth=60, max_features=8,
           max_leaf_nodes=None, min_impurity_decrease=0.0,....]

我希望列表中的每個估計器/函數都適用於數據框中的每一行。

如果我不將數據轉換為數據幀,則boston['data']將返回2D數組。 我可以使用兩個for loops來完成上述操作。 假設X是2D數組,那么我可以執行以下操作

for x in range(len(X)):
    vals = []
    for estimator in model.estimators_:
        vals.append(estimator.predict(X[x])[0])

我不想使用2D數組選項,因為我想保留DataFrame的索引信息以備將來使用。

在最新版本的pandasdf.agg應該能夠做到這一點。

不幸的是,當axis=1時,當前版本似乎已損壞: https//github.com/pandas-dev/pandas/issues/16679

這是一種解決方法:

X.T.agg(estimators).T

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM