Search code examples
pandaskdb

Save pandas dataframe in kdb/q


What is the best way to save a pandas dataframe in kdb? Are there any libraries that can make it easier?

The below code can apparently be used to loas something from kdb, but how do I save a dataframe into it?

from qpython import qconnection

with qconnection.QConnection(host = 'localhost', port = 5001, pandas = True) as q:
    ds = q('(1i;0Ni;3i)', pandas = True)
    print(ds)

Solution

  • To save a dataframe in KDB+ with qPython one can use the sync method of the QConnection class. Set the first parameter to a string defining a q function that assigns its parameter to a global variable and send the dataframe as the second parameter. Something like this:

    from qpython import qconnection
    import pandas as pd
    df = pd.DataFrame({'sym':['abc','def','ghi'],'price':[10.1,10.2,10.3]})
    with qconnection.QConnection(host = 'localhost', port = 5001, pandas = True) as q:
        q.sync('{t::x}',df)
    

    Note that you need to use a double colon :: in the function definition so that the parameter is assigned to a global variable t rather that a local variable.