【问题标题】:How can i save a Panda dataframe to a django model?如何将 Panda 数据框保存到 django 模型?
【发布时间】:2018-06-15 13:51:25
【问题描述】:

我正在尝试使用 panda 读取 csv 文件并对其进行解析,然后将结果上传到我的 django 数据库中。好吧,现在我将每个数据帧转换为一个列表,然后遍历该列表以将其保存在数据库中。但是当每个列的列表都很大时,我的解决方案效率很低。我怎样才能让它变得更好?

 fileinfo = pd.read_csv(csv_file, sep=',',
                        names=['Series_reference', 'Period', 'Data_value', 'STATUS',
                               'UNITS', 'Subject', 'Group', 'Series_title_1', 'Series_title_2',
                               'Series_title_3','Series_tile_4','Series_tile_5'],
                        skiprows = 1)

# serie = fileinfo[fileinfo['Series_reference']]
s = fileinfo['Series_reference'].values.tolist()
p = fileinfo['Period'].values.tolist()
d = fileinfo['Data_value'].values.tolist()
st = fileinfo['STATUS'].values.tolist()
u = fileinfo['UNITS'].values.tolist()
sub = fileinfo['Subject'].values.tolist()
gr = fileinfo['Group'].values.tolist()
stt= fileinfo['Series_title_1'].values.tolist()

while count < len(s):    
    b = Testdata(
        Series_reference = s[count],
        Period = p[count],
        Data_value = d[count],
        STATUS = st[count],
        UNITS = u[count],
        Subject = sub[count],
        Group = gr[count],
        Series_title_1 = stt[count]
    )
    b.save()
    count = count + 1

【问题讨论】:

  • 我的第一直觉会使用 pandas.DataFrame.to_dict 然后遍历 dict 以创建一堆内置的 Testdata 实例。我发现这个 SO 链接很有帮助。 stackoverflow.com/questions/1639174/…

标签: python django pandas


【解决方案1】:

您可以使用熊猫apply 功能。您可以通过axis=1 将给定函数应用于每一行:

df.apply(
    creational_function, # Method that creates your structure
    axis=1, # Apply to every row
    args=(arg1, arg2) # Additional args to creational_function
)

creational_function 中,接收到的第一个参数是行,您可以在其中访问特定列,就像原始数据框一样

def creational_function(row, arg1, arg2):
    s = row['Series_reference']
    # For brevity I skip the others arguments...
    # Create TestData
    # Save

请注意,arg1arg2 对于每一行都是相同的。

如果您想对创建的TestData 对象执行更多操作,可以更改creational_function 以返回一个值,然后df.apply 将返回一个列表,其中包含传递的函数返回的所有元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-20
    • 2023-03-28
    • 2016-07-07
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    相关资源
    最近更新 更多