【问题标题】:Pandas updating changes to appended values that are modified afterwards熊猫更新对随后修改的附加值的更改
【发布时间】:2020-01-29 08:40:27
【问题描述】:

我有一个代码,我可以在其中打开一个电子表格,阅读它,然后将其保存在一个多维数组中并查找字符串匹配项。

import pandas as pd
import numpy as np

file = pd.ExcelFile("File.xlsx")

top100 = []
pub = []
ind = []
missed = []

for i in range(len(file.sheet_names)):
    year = 2005 + i
    df_aux = pd.read_excel(file, str(year))
    top100.append(df_aux)
    df_aux2 = pd.read_excel("AnotherFile"+str(year+".xls")
    pub.append(df_aux2)
    ind_aux = []
    missed_aux = []
    df_aux2['Contributors'] = df_aux2['Contributors'].str.replace(" ",'')
    df_aux['Institution'] = df_aux['Institution'].str.replace(" ",'')    
    for j in range(len(df_aux2)):
        a = np.where(df_aux2['Contributors'][j] == df_aux['Institution'])[0]
        if len(a)>0:
            ind_aux.append(j)
        else:
            missed_aux.append(j)
    ind.append(ind_aux)
    missed.append(missed_aux)

代码的目的是在列表中查找匹配项。因为它们是字符串并且有一些问题,所以我删除了所有空格。我的理解是,这不应该改变已经附加的内容,但是如果我打印例如 pub[0] 我会得到所有没有空格的单词。

print(pub[0]['Contributors'])
"Therearenospaces"

为什么会这样?

【问题讨论】:

    标签: python arrays string pandas


    【解决方案1】:

    发生这种情况是因为使用pub.append(df_aux2),您实际上并没有两个不同的值。赋值只是将引用复制到一个值,而不是实际的数据帧,所以附加的 df_aux2 和正式的 df_aux2 在赋值后引用同一个变量。 要实际复制列表,您可以使用list.copy() 方法,我相信该方法从 Python 3.3 开始可用。如果我没记错的话,这应该可以解决问题:

    new_pub = pub.append(df_aux2).copy()
    

    【讨论】:

    • 我应该把它放在代码的什么地方?我尝试替换pub.append(df_aux2),但出现以下错误:AttributeError: 'NoneType' object has no attribute 'copy'
    【解决方案2】:

    根据 Celius Stingher 的回应,以下方法有效:

    new_pub = pub.copy()
    

    【讨论】:

    • 将编辑我的答案以考虑这种情况,谢谢
    猜你喜欢
    • 2019-12-16
    • 2021-12-29
    • 1970-01-01
    • 2017-06-24
    • 2017-03-08
    • 2018-08-21
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多