2017-02-23 79 views
2

我想讀取類型爲map<string, int>的cassandra列族中的數據並希望將其轉換爲Pandas數據框。我進一步想用Python在Python中訓練模型,如虹膜種類分類中提到的here如何將Cassandra地圖轉換爲Pandas Dataframe

如果我會用csv來訓練模型。然後,它會是這個樣子的:

label, f1, f2, f3, f4, f5 
    0 , 11 , 1, 6 , 1, 2 
    1 , 5, 5, 1 , 2, 6 
    0 , 12, 9, 3 , 6, 8 
    0 , 9, 3, 8, 1, 0 

卡桑德拉列族:

    FeatureSet     | label 

{'f1': 11, 'f2': 1, 'f3': 6, 'f4': 1, 'f5': 2} |  0 
{'f1': 5, 'f2': 5, 'f3': 1, 'f4': 2, 'f5': 6} |  1 
{'f1': 12, 'f2': 9, 'f3': 3, 'f4': 6, 'f5': 8} |  0 
{'f1': 9, 'f2': 3, 'f3': 8, 'f4': 1, 'f5': 0} |  0 

代碼:

import pandas as pd 
from sklearn2pmml import PMMLPipeline 
from sklearn.tree import DecisionTreeClassifier 
from cassandra.cluster import Cluster 

CASSANDRA_HOST = ['172.16.X.Y','172.16.X1.Y1'] 
CASSANDRA_PORT = 9042 
CASSANDRA_DB = "KEYSPACE" 
CASSANDRA_TABLE = "COLUMNFAMILY" 

cluster = Cluster(contact_points=CASSANDRA_HOST, port=CASSANDRA_PORT) 
session = cluster.connect(CASSANDRA_DB) 

sql_query = "SELECT * FROM {}.{};".format(CASSANDRA_DB, CASSANDRA_TABLE) 

df = pd.DataFrame() 

for row in session.execute(sql_query): 
      What should i write here and get X_train, Y_train in pandas dataframe 



iris_pipeline = PMMLPipeline([ 
    ("classifier", DecisionTreeClassifier()) 
]) 
iris_pipeline.fit(X_train, Y_train) 

回答

1

您可以使用this approach

import pandas as pd 
from cassandra.cluster import Cluster 

def pandas_factory(colnames, rows): 
    return pd.DataFrame(rows, columns=colnames) 

CASSANDRA_HOST = ['172.16.X.Y','172.16.X1.Y1'] 
CASSANDRA_PORT = 9042 
CASSANDRA_DB = "KEYSPACE" 
CASSANDRA_TABLE = "COLUMNFAMILY" 

cluster = Cluster(contact_points=CASSANDRA_HOST, port=CASSANDRA_PORT) 
session = cluster.connect(CASSANDRA_DB) 

session.row_factory = pandas_factory 
session.default_fetch_size = None 

query = "SELECT * FROM {}.{};".format(CASSANDRA_DB, CASSANDRA_TABLE) 

rslt = session.execute(query, timeout=None) 
df = rslt._current_rows 
+0

我已經試過這種方法。但是'只打印輸出中的映射鍵(f1,f2,f3,f4)「僅打印df'。當我打印'df.values'時,它給出了[OrderedMapSerializedKey([(u'f1',11),(u'f2',1),(u'f3',6),(u'f4', 1),(u'f5',2)])]'。我無法使用這些值來訓練它。它應該返回數字值和第一行中的標題。就像我在csv中提到的一樣 – Naresh

1

我發佈了一個工作解決方案here爲同一個問題讀取OrderedMapSerializedKey卡桑德拉地圖字段作爲您的數據框字典。


編輯:

在以前的解決方案,我只更換第一個(0)級卡桑德拉數據集的行(rows是元組的列表,每個元組是在卡桑德拉行)

from cassandra.util import OrderedMapSerializedKey 

def pandas_factory(colnames, rows): 

    # Convert tuple items of 'rows' into list (elements of tuples cannot be replaced) 
    rows = [list(i) for i in rows] 

    # Convert only 'OrderedMapSerializedKey' type list elements into dict 
    for idx_row, i_row in enumerate(rows): 

     for idx_value, i_value in enumerate(i_row): 

      if type(i_value) is OrderedMapSerializedKey: 

       rows[idx_row][idx_value] = dict(rows[idx_row][idx_value]) 

    return pd.DataFrame(rows, columns=colnames) 
0

除了MaxU答案,如果你想看到你的結果作爲數據幀,所有你需要做的就是增加一行:

df = pd.DataFrame(rslt._current_rows)

相關問題