2

Given this data frame...:

DF = pd.DataFrame({'COL1': ['A', 'B', 'C', 'D','D','D'], 
                   'COL2': [11032, 1960, 11400, 11355, 8, 7], 
                   'year': ['2016', '2017', '2018', '2019', '2020', '2021']})
DF

   COL1 COL2    year
0   A   11032   2016
1   B   1960    2017
2   C   11400   2018
3   D   11355   2019
4   D   8       2020
5   D   7       2021

If the following conditions are met:

  1. COL1 = 'D'
  2. year = '2021' (please treat it as a string)

Then change the value in COL2 to 100.

Alternatively, what if year is treated as an int?

1 Answer 1

3

This is a typical use case of loc. When selecting multiple criteria for the row selection, an example of a cond 1 and (cond 2 or cond 3) pattern would be df.loc[(condition 1) & ((condition 2) | (condition 3), 'selected columns'].

DF.loc[(DF.COL1 == 'D') & (DF.year == '2021'), 'COL2'] = 100

If the year were an integer, you could simply amend it as follows to capture both integers and strings:

DF.loc[(DF.COL1 == 'D') & (DF.year.astype(int) == 2021), 'COL2'] = 100
Sign up to request clarification or add additional context in comments.

3 Comments

What if I wanted to use a column name in place of 'D' and 2021 to iterate through two columns containing values including 'D' and 2021 and change the corresponding value per row in 'COL2'?
I'm not sure I follow. Can you post a new question with sample data and desired result?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.