Pandas Settingwithcopywarning: A value is trying to be set on a copy of a Slice from a Dataframe

Asked

Viewed 842 times

2

I want to copy an element of a dataframe and insert it into another dataframe.

In essence there is a dataframe with name x area and another that I need to load with the data of the area, from the comparison of the name in the first dataframe. The code is working, but gives this title Warning.

What am I doing:

for i in range(0,len(NOVOS_ABERTOS_VIVO)):
    for j in range(0,len(AREA_VERSUS_COLABORADOR)):
        if NOVOS_ABERTOS_VIVO.loc[i]['Originator'] == AREA_VERSUS_COLABORADOR.loc[j]['Originator']:
            TEMP=AREA_VERSUS_COLABORADOR.loc[j]['Área']
            NOVOS_ABERTOS_VIVO.loc[i]['Área']=str(TEMP)

I also made:

for i in range(0,len(NOVOS_ABERTOS_VIVO)):
    for j in range(0,len(AREA_VERSUS_COLABORADOR)):
        if NOVOS_ABERTOS_VIVO.loc[i]['Originator'] == AREA_VERSUS_COLABORADOR.loc[j]['Originator']:
            AREA_VERSUS_COLABORADOR.loc[j]['Área']=NOVOS_ABERTOS_VIVO.loc[i]['Área'] 

1 answer

3


Hello, Guido. Welcome back!

That one Warning can be easily solved by modifying your code in this way:

for i in range(0,len(NOVOS_ABERTOS_VIVO)):
    for j in range(0,len(AREA_VERSUS_COLABORADOR)):
        if NOVOS_ABERTOS_VIVO.loc[i]['Originator'] == AREA_VERSUS_COLABORADOR.loc[j]['Originator']:
            AREA_VERSUS_COLABORADOR.loc[j,'Área']=NOVOS_ABERTOS_VIVO.loc[i,'Área']

Note that instead of writing df.loc[linha][coluna], was written df.loc[linha,coluna]. This is the recommended way to do this type of operation for performance.

In the first form (df.loc[linha][coluna]) what is being done is a linear and independent call for operations, or a chain call. First the pandas returns all columns of the dataframe of the desired row to only return the column.

On the other hand, the second form (df.loc[linha,coluna]) allows the pandas treat your search as a single entity, greatly improving speed.

References:

http://pandas.pydata.org/pandas-docs/stable/indexing.html#Indexing-view-versus-copy

  • Excellent!!! Thank you very much!!!!

  • You are welcome. If the answer has solved your problem, please accept the answer by clicking on the check mark on the left side of the answer. See this post for more information https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-reply

Browser other questions tagged

You are not signed in. Login or sign up in order to post.