Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Dataframe row selection combined condition index- and column values

Tags:

python

pandas

I want to select rows from a dataframe based on values in the index combined with values in a specific column:

df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [0, 20, 30], [40, 20, 30]], 
                  index=[4, 5, 6, 7], columns=['A', 'B', 'C'])


    A   B   C
4   0   2   3
5   0   4   1
6   0  20  30
7  40  20  30

with

df.loc[df['A'] == 0, 'C'] = 99

i can select all rows with column A = 0 and replace the value in column C with 99, but how can i select all rows with column A = 0 and the index < 6 (i want to combine selection on the index with selection on the column)?

like image 872
Egirus Ornila Avatar asked Sep 04 '18 14:09

Egirus Ornila


People also ask

How do I select a specific row and column in pandas?

To select a single value from the DataFrame, you can do the following. You can use slicing to select a particular column. To select rows and columns simultaneously, you need to understand the use of comma in the square brackets.


1 Answers

You can use multiple conditions in your loc statement:

df.loc[(df.index < 6) & (df.A == 0), 'C'] = 99
like image 76
sacuL Avatar answered Nov 06 '22 04:11

sacuL