Explore Courses Blog Tutorials Interview Questions
0 votes
in Data Science by (17.6k points)

Say I have the following dataframe:


What is the most efficient way to update the values of the columns feat and another_feat where the stream is number 2?

Is this it?

for index, row in df.iterrows():

    if df1.loc[index,'stream'] == 2:

       # do something

UPDATE: What to do if I have more than a 100 columns? I don't want to explicitly name the columns that I want to update. I want to divide the value of each column by 2 (except for the stream column).

So to be clear what my goal is:

Dividing all values by 2 of all rows that have stream 2, but not changing the stream column

1 Answer

0 votes
by (41.4k points)

c       2        aaaa         aaaa

b       2        aaaa         aaaa

Use loc for updating two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'

print df1

   stream        feat another_feat

a       1  some_value   some_value

d       3  some_value   some_value

If you are interested to learn Pandas visit this Python Pandas Tutorial.

Related questions

Browse Categories