Sam Rds Sam Rds - 3 months ago 12
Python Question

I can't assignment a value to the cell python pandas

I have the following code:

for i in range(len(list_sort)):
list_sort[i] = list_sort[i].reset_index()
classification = 1
list_sort[i].set_value(0, list_column[k], classification)
for j in range(len(df))[1::]:
if(list_sort[i].ix[j][1] == list_sort[i].ix[j-1][1]):
list_sort[i].ix[j][2] = classification
else:
classification += 1
list_sort[i].ix[j][2] = classification
k += 2
list_sort[i] = list_sort[i].set_index('index')


I have a list_sort that contain several DataFrame. Each one has a column that I need to compare the current line with the previous line.

This is part of the result when I compare a column where all values are type
int
:

ACESSO_PORTAL CLASSIFICACAO_ACESSO_PORTAL
index
19 973693 1
8 954719 2
27 918459 3
1 908029 4
4 865346 5
31 754591 6
35 743908 7
23 733344 8
14 702816 9


This is part of the result when I compare a column where all values are type
float
:

TOTAL_PRODUTOS CLASSIFICACAO_TOTAL_PRODUTOS
index
19 118798.57 1
1 92415.46 0
2 82987.19 0
31 82228.57 0
23 80109.00 0
0 72606.59 0
34 69385.11 0
17 63794.19 0
33 61328.62 0


Each DataFrame has the index and two columns.

As you can see, it doesn't work with float.

I have not idea why happened this. I try use
set_value
, but didn't work.

Answer

You are trying to set a value on a copy:

C:\Anaconda2\lib\site-packages\ipykernel__main__.py:10: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

On these lines:

        #This one...
        list_sort[i].ix[j][2] = classification
    else:
        classification += 1
        # And this one
        list_sort[i].ix[j][2] = classification

I don't think it's working with integers either. I can't know for sure, because you did not provide sample data.

Try using iloc instead:

        list_sort[i].iloc[j, 2] = classification
        #       Here ^
    else:
        classification += 1
        list_sort[i].iloc[j, 2] = classification
        #   And here ^