Select and change slice in pandas dataframe integer index

I have a dataframe as shown below:

df = pd.DataFrame([[1,2],[10,20],[10,2],[1,40]],columns = ['a','b'])
    a   b
0   1   2
1   10  20
2   10  2
3   1   40

I want to select the column bwhere a == 1, the following classic choice:

df[df.a == 1].b
    a   b
0   1   2
3   1   40

Then I want to select the ith row of this sub-diaphragm, which is not a row with index i. There are also several ways, for example:

df[df.a == 1].b.iloc[[1]]
Output: 
3    40
Name: b, dtype: int64

So far so good. The problem is that when I try to change the value that I received, indeed, this selection method gives a copy of the slice of the data block, not the object itself. Therefore, I cannot change it in place.

test[test.a == 1].b.iloc[[1]] = 3
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

I do not know in what part the “copy” problem lies, since the following two give the same problem:

test.iloc[[3]].b = 3
test[test.a == 1].b = 3

, : ( a) ( , )?

+4
1

loc :

In[178]:
df.loc[df.loc[df['a'] == 1,'b'].index[1], 'b'] = 3
df

Out[178]: 
    a   b
0   1   2
1  10  20
2  10   2
3   1   3

, df df['a'] == 1, df 'b':

In[179]:
df.loc[df['a'] == 1,'b']

Out[179]: 
0    2
3    40
Name: b, dtype: int64

:

In[180]:
df.loc[df['a'] == 1,'b'].index[1]

Out[180]: 3

loc.

test[test.a == 1].b.iloc[[1]] = 3 , .

+3

Source: https://habr.com/ru/post/1679780/


All Articles