python - How to add value to column conditional on other column -


in pandas, how possible add value column conditional on string in other column? (something resembling 2-dimensional slice operation?)

for example, having dataframe this:

df = pd.dataframe({'name': ['foo', 'foo', 'bar', 'bar'],                    'colx': [1, 2, 3, 4],                    'coly': [5, 6, 7, 8]}) 

how possible add 10 column colx if column name foo?

the resulting df this:

   colx  coly name 0    11     5  foo 1    12     6  foo 2     3     7  bar 3     4     8  bar 

you can use loc operator perform slicing when want modify values:

df.loc[df.name == 'foo','colx'] += 10 

the uses underlying slicing methods of pandas way faster looping or using apply on dataframe. allthemore if dataframe gets big.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -