使用python编写insert查询,将动态数量的dataframe列插入cassandra表

qoefvg9y  于 2021-06-13  发布在  Cassandra
关注(0)|答案(1)|浏览(347)

我有一个30列的cassandra表和一个dataframe,它包含用户选择的任意数量的列,或者用户上传的csv文件。
例如,我的cassandra表有30个频道名,如频道1、频道2。。channel_30和几个额外的列,如product、region等,我的Dataframe有5个通道名,如channel_1、channel_2..channel_5和2个额外的列:date和model name如何编写一个insert查询,该查询遍历我的Dataframe列并按如下方式创建查询:

data = pd.DataFrame()
...
for _, row in data.iterrows():

            session.execute("""INSERT INTO cass_table (product, region , model, date, (channel names in dataframe ex.channel_1, \
                    channel_2, channel_3, channel_4, channel_5) \
                    VALUES (%s, %s, %s, %s, <no of channels: %s, %s, %s, %s, %s>)""" ,\
                    (product, region, row['model_name'], row['date'], <other remaining columns like row["channel_1"], row["channel_2"],\
                    row["channel_3"], row["channel_4"], row["channel_5"]>))

我试过这个:

channel_list = ['channel_1', 'channel_2', 'channel_3', 'channel_4', 'channel_5']
session.execute("""INSERT INTO cass_table(product, region , model, date, \
                    """ + str(' ,'.join('channel_{}_cont'.format(i) for i,c in enumerate(channel_list, 1))) + """) ,\
                    VALUES (%s, %s, %s, %s"""+ str(''.join(', %s'*no_of_channels)), """)""" \
                    (product, region, row['model_name'], row[date_col] , ','.join(row["'"+channel_list+"'"])))

但这会产生错误:“str对象不可调用”
我该怎么做?

nom7f22z

nom7f22z1#

在实践中,这应该是可行的,但是您编写查询的方式有一些错误。
你错过了一个 , 在查询模式和值之间
在生成要插入的值的元组时,要使用 * 接线员。它将扩展列表中的每个元素作为函数的参数。看到这个问题了吗

query = (
    "INSERT INTO cass_table (product, region , model, date, "
    + ', '.join(channel_list) + ') '
    + " VALUES (%s, %s, %s, %s, " + ', '.join(['%s'] * len(channel_list)) + ")"
)

values = (product, region, row['model_name'], row[date_col] , *[row[c] for c in channel_list])
session.execute(query, values)

相关问题