0

I try to modify the value of cells in a dataframe, conditionnal to their value. the dataframe dataTrad(50k, 20) as 21 columns, one of which is called 'reindex'. I want to bring the value of any 'reindex' cell down to 0 as soon as its original value is lower than a variable (mlp).

I tried : dataTrad[i, 'reindex'][dataTrad[i, 'reindex'] < mlp] = 0 with a loop on i with the range(len(dataTrad)), as well as dataTrad.loc[(dataTrad.reindex < malp),'reindex']=0, but none of these two methods worked.

In my precise example, I had mlp = 60 len(dataTrad) = 57830

What do I do wrong, and how could I solve this ? Thanks a lot in advance.

JDE65
  • 89
  • 2
  • 8
  • 1
    Welcome to StackOverflow. Please include a small sample of your data along with your desired results. Take a look at [how-to-make-good-pandas-examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). – Shubham Sharma Jun 24 '20 at 08:10

2 Answers2

0

I would try something like this

dataTrad['reindex'] = dataTrad['reindex'].apply(lambda x: 0 if (x<mlp) else x)

I'm sure there should be another way, like a inplace parameter but try this for now

Let me know if it works :)

SaulVP
  • 90
  • 6
0

I'm not 100% clear on what the 'reindex' column is, is it a counter that you want to 'reset' each time 'mpl' reaches a certain point, or a value that you want to use unless 'mlp' reaches a certain point.

For the second, a simple apply / lambda combo should do what you need, something like this:

dataTrad['reindex'] = dataTrad.apply(lambda row: row['reindex'] if x > row['mlp'] else 0) 

Otherwise, a cumulative rolling count that resets is 'slightly' more complicated, but is covered pretty well here if you need it.

houseofleft
  • 347
  • 1
  • 12
  • Thanks. I get an error as follows : File "", line 1 dataTrad['reindex'] = dataTrad.apply(lamba row: row['reindex'] if x > row['mlp'] else 0) ^ SyntaxError: invalid syntax – JDE65 Jun 24 '20 at 08:48
  • woops! I'd written 'lamba' not 'lambda' which would definitely cause an error since 'lamba' isn't a thing (have edited now, let me know how it runs) – houseofleft Jun 24 '20 at 09:52