Python列表中有熊猫df,似乎没有复制到新列表?

Python列表中有熊猫df,似乎没有复制到新列表?,python,pandas,list,copy,slice,Python,Pandas,List,Copy,Slice,所以,我对Python相当陌生,大约6个月;但我知道列表占用相同的内存,除非你从旧列表复制新列表 但我在使用列表时看到了奇怪的行为……试图从csv加载数据帧,然后转换为列表;最后的任务是确保我有一个模板作为基础 从template.xlsx加载模板 创建列表数据的新行 模板的默认新行 更新新行 将新行添加到主控形状 然后在将结果写入新的CSV之前重复此部分 excel_IND_TEMPLATE_df = pd.read_excel('template.xlsx',

所以,我对Python相当陌生,大约6个月;但我知道列表占用相同的内存,除非你从旧列表复制新列表

但我在使用列表时看到了奇怪的行为……试图从csv加载数据帧,然后转换为列表;最后的任务是确保我有一个模板作为基础

从template.xlsx加载模板

创建列表数据的新行 模板的默认新行 更新新行 将新行添加到主控形状 然后在将结果写入新的CSV之前重复此部分

excel_IND_TEMPLATE_df = pd.read_excel('template.xlsx', 
                              sheet_name='IND_TEMPLATE', dtype=str)
excel_IND_TEMPLATE_df.fillna('', inplace=True)

ind_template = excel_IND_TEMPLATE_df.loc[0:0, :].values.tolist()

## using list

ind_template_copy1 = list(ind_template)
ind_template[0][0] = 'test1'
print(ind_template)
print(ind_template_copy1)

## using .copy()

ind_template_copy2 = ind_template.copy()
ind_template[0][0] = 'test2'
print(ind_template)
print(ind_template_copy2)

## using slice

ind_template_copy3 = ind_template[:]
ind_template[0][0] = 'test3'
print(ind_template)
print(ind_template_copy3)
这将产生以下结果:-

[['test1', 'Y']]
[['test1', 'Y']]

[['test2', 'Y']]
[['test2', 'Y']]

[['test3', 'Y']]
[['test3', 'Y']]

因此,本质上使用list、.copy和slice都会强制新列表与原始列表具有相同的内存。。。?我认为这会起作用…并在两个单独的列表中结束???

您可以尝试使用
copy.deepcopy

import copy

ind_template_copy2 = copy.deepcopy(ind_template)
ind_template[0][0] = 'test2'
print(ind_template)
print(ind_template_copy2)
ind_模板的输出=['a'、'b']、['c'、'd']]

[['test2', 'b'], ['c', 'd']]
[['a', 'b'], ['c', 'd']]

谢谢…这很有效。那么你认为raw.copy()、list和slice[:]有缺陷吗??因为我相信他们应该工作。。。不管怎样,那太好了,再次谢谢你!如果我的ans帮助了你,请接受我的ans作为最好的ans。谢谢!见和/或。这里的一切都按预期工作:您创建了一个新列表,但列表中的项目本身实际上是相同的对象,因此当您更新它们时,您会看到它们在原始列表和副本中被更新。您需要一个deepcopy来递归地创建新的独立对象。。