简体   繁体   中英

Assign value via iloc to Pandas Data Frame

Code snippet:

    for row in df.itertuples():
        current_index = df.index.get_loc(row.Index)
        if current_index < max_index - 29:

            if df.iloc[current_index + 30].senkou_span_a == 0.0:
                df.iloc[current_index + 30].senkou_span_a = 6700


            if df.iloc[current_index + 30].senkou_span_b == 0.0:
                df.iloc[current_index + 30].senkou_span_b = 6700.0

the last line where I am assigning a value via iloc, it goes through, but the resultant value is 0.0. I ran into this before where I was assigning the value to a copy of the df, but that doesn't seem to be the case this time. I have been staring at this all day. I hope it is just something silly.

df is timeseries(DateTimeIndex) financial data. I have verified the correct index exists, and no exceptions are thrown.

There is other code to assign values and those work just fine, omitted that code for the sake of brevity.

EDIT

This line works: df.iloc[current_index + 30, df.columns.get_loc('senkou_span_b')] = 6700

why does this one, and not the original?

I'm not sure exactly what's causing your problem (I'm pretty new to Python), but here's some things that came to mind that might be helpful:

  1. Assuming that the value you're replacing is always 0 or 0.0, maybe try switching from = to += to add instead of assign?
  2. Is your dataframe in tuple format when you attempt to assign the value? Your issue might be that tuples are immutable.
  3. If senkou_span_a refers to a column that you're isolating, maybe try only using iloc to isolate the value like df.iloc[(currentindex + 30), 1] == 0.0

Hope this helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM