Reputation: 729
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?
Upvotes: 1
Views: 9523
Reputation: 4070
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
Upvotes: 3
Reputation:
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
Upvotes: 6