Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use loc and iloc together in pandas

Say I have the following dataframe, and I want to change the two elements in column c that correspond to the first two elements in column a that are equal to 1 to equal 2.

>>> df = pd.DataFrame({"a" : [1,1,1,1,2,2,2,2], "b" : [2,3,1,4,5,6,7,2], "c" : [1,2,3,4,5,6,7,8]})
>>> df.loc[df["a"] == 1, "c"].iloc[0:2] = 2
>>> df
   a  b  c
0  1  2  1
1  1  3  2
2  1  1  3
3  1  4  4
4  2  5  5
5  2  6  6
6  2  7  7
7  2  2  8

The code in the second line doesn't work because iloc sets a copy, so the original dataframe is not modified. How would I do this?

like image 779
Alex Avatar asked Jun 19 '16 19:06

Alex


People also ask

Can you use ILOC and loc together?

In this case, loc and iloc are interchangeable when selecting via a single value or a list of values. Note that loc and iloc will return different results when selecting via slice and conditions.

Where can I use loc and ILOC?

loc() and iloc() are one of those methods. These are used in slicing data from the Pandas DataFrame. They help in the convenient selection of data from the DataFrame in Python. They are used in filtering the data according to some conditions.

Is ILOC slower than loc?

iloc[[ id ]] (with a single-element list) takes 489 ms, almost half a second, 1,800x times slower than the identical .


1 Answers

A dirty way would be:

df.loc[df[df['a'] == 1][:2].index, 'c'] = 2
like image 136
ayhan Avatar answered Sep 21 '22 19:09

ayhan