2

i try to run a code where i go through a column in a pandas dataframe like that:

for item in df['delta']:
    if float(item) < 0:
        print(item)

Whenever i detect an item with a value below 0, i want to add 1,000,000 and put the result back into the dataframe.

I tried something like:

df['delta'][item] = float(item) + 1000000

but then i get a key error.

How can i access the current location of the for-loop?

FBruzzesi
  • 5,451
  • 3
  • 9
  • 26
haddock
  • 33
  • 4
  • the answer to this question is already present: https://stackoverflow.com/questions/31569384/set-value-for-particular-cell-in-pandas-dataframe-with-iloc – Roberto Bellarosa Dec 03 '19 at 16:26
  • This is Pandas 101. Have you made any effort whatsoever to solve this yourself?! Please see: [ask], https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users. – AMC Dec 03 '19 at 17:16

2 Answers2

2

Suppose you have

    df = pd.DataFrame({'col_1': [0,1,2,3,4,5,-1,-2,-3]})

   col_1
0      0
1      1
2      2
3      3
4      4
5      5
6     -1
7     -2
8     -3

You can simply use loc and += operator to have

df.loc[df['col_1'] < 0, 'col_1'] += 10

   col_1
0      0
1      1
2      2
3      3
4      4
5      5
6      9
7      8
8      7
rafaelc
  • 48,227
  • 12
  • 46
  • 72
0

I'd recommend using the built-in apply() function for this:

df['delta'] = df['delta'].apply( lambda item: float(item) + 1000000 if float(item) < 0 else item )
jackaloops
  • 19
  • 4