【问题标题】:Python Lists with pandas df, seemingly not copying to a new list?带有熊猫df的Python列表,似乎没有复制到新列表?
【发布时间】:2021-02-15 02:56:39
【问题描述】:

所以,我对 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 个单独的列表结尾??

【问题讨论】:

标签: python pandas list copy slice


【解决方案1】:

你可以试试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', 'b'], ['c', 'd']]
[['a', 'b'], ['c', 'd']]

【讨论】:

  • 谢谢...效果很好。那么你认为原始的 .copy()、list 和 slice[:] 有错误吗?因为我确信他们应该工作......无论如何......那再次感谢
  • YW!如果我的回答对你有帮助,请接受我的回答作为最好的回答。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-04-17
  • 2016-02-20
  • 2021-02-25
  • 1970-01-01
  • 1970-01-01
  • 2022-11-15
  • 2021-04-30
  • 2016-09-23
相关资源
最近更新 更多