Home > Blockchain >  Python Pandas: alter each cell in column based on its row
Python Pandas: alter each cell in column based on its row

Time:04-08

If I have a pandas data structure, how can I alter each cell in a column based on a neighboring cell

for example

               word  pos  neg  unsup
0         poker-fac    1    1      1
1           giggler    1    1      1
2           pre-cod    1    1      1
3       single-hand    1    1      1
4      correctly.it    1    1      1

given this pd struct, vocab, how could I set vocab["pos"] to equal a value based on the corresponding word

ie lets say i wanted "pos" to equal the number of g's in each word it would turn into this

               word  pos  neg  unsup
0         poker-fac    0    1      1
1           giggler    3    1      1
2           pre-cod    0    1      1
3       single-hand    1    1      1
4      correctly.it    0    1      1

I tried this but it just ran forever:

for word, prob in zip(vocab["word"],vocab["pos"]):
    prob = pos_tokens.count(word)

CodePudding user response:

You can use:

df['pos'] = df['word'].str.count('g')
  • Related