1

assume I have a dataframe. I would like to modify a list of rows with certain value.

For example, below is my dataframe.

df = pd.DataFrame({
"strings":["A", "B", "C", "D", "E"], 
  "value":["a", "b", "c", "d", "f"], 
  "price":["1", "2", "3", "4", "5"]})

And I want to replace all cells with '0' in row C, D, and E, which is like below. Rows = ['C', 'D', 'E']

df = pd.DataFrame({
"strings":["A", "B", "C", "D", "E"], 
  "value":["a", "b", "0", "0", "0"], 
  "price":["1", "2", "0", "0", "0"]})

I know we can achieve this by simply giving the rows' name and certain value, but as we have lots of rows to be modified, how could we do this more efficiently using pandas?

Anyone hint please?

2
  • Do you mean COLUMN C, D, E? C, D and E are not rows Commented May 3, 2016 at 15:16
  • @dahui C, D, E are not Columns either Commented May 3, 2016 at 15:17

2 Answers 2

6

If I understood correctly, you want all the values in columns "price" and "value" to be set to zero for rows where column "strings" has values either C, D or E.

df.loc[df.strings.isin(["C", "D", "E"]), df.columns.difference(["strings"])] = 0
df
Out[82]: 
  price strings value
0     1       A     a
1     2       B     b
2     0       C     0
3     0       D     0
4     0       E     0
Sign up to request clarification or add additional context in comments.

6 Comments

difference is better :)
Thanks, but if I have hundreds of rows required to be modified, what should I do??
@Sakura How do you identify the rows that should be modified? Are they in a list or something like that? Do they follow a rule?
That is a list of them, no particular rule.
@Sakura then you can just pass the name of the list. For example df.loc[df.strings.isin(name_of_the_list), df.columns.difference(["strings"])] = 0
|
3

Here is another way of doing it,

Consider your data is like this:

  price strings value
0     1       A     a
1     2       B     b
2     3       C     c
3     4       D     d
4     5       E     f

Now lets make strings column as the index:

df.set_index('strings', inplace=True)

#Result
        price value
strings
A           1     a
B           2     b
C           3     c
D           4     d
E           5     f

Now set the values of rows C, D, E as 0

df.loc[['C', 'D','E']] = 0

#Result
        price value
strings
A           1     a
B           2     b
C           0     0
D           0     0
E           0     0

Comments

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.