如何解决带有df熊猫的Python列表,似乎没有复制到新列表?
因此,我刚接触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']]
因此本质上使用列表,.copy和slice都强制新列表与原始列表具有相同的内存...?我以为这行得通...并以2个单独的列表结尾??
解决方法
您可以尝试使用copy.deepcopy
:
import copy
ind_template_copy2 = copy.deepcopy(ind_template)
ind_template[0][0] = 'test2'
print(ind_template)
print(ind_template_copy2)
ind_template = [['a','b'],['c','d']]
的输出:
[['test2','d']]
[['a','d']]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。