0

I have a dataframe:

index     value
    0        0
    1        0
    2        0
    3        0
    4        0
    5        0
    6        0
    7        0
    8        0
    9        0
    10       0
    11       0
    12       0
    13       0
    14       0
    15       0
    16       0
    17       0
    18       0
    19       0
    20       0
    21       0
    22       0
    23       0
    24       0
    25       0
    26       0
    27       0
    28       0
    29       0
            ..
    57571    0
    57572    0
    57573    0
    57574    0
    57575    0
    57576    0
    57577    0
    57578    0
    57579    0
    57580    0
    57581    0
    57582    0
    57583    0
    57584    0
    57585    0
    57586    0
    57587    0
    57588    0
    57589    0
    57590    0
    57591    0
    57592    0
    57593    0
    57594    0
    57595    0
    57596    0
    57597    0
    57598    0
    57599    0
    57600    0

and 2 arrays:

A=np.arange(0,57601,1800) 
A= [    0,  1800,  3600,  5400,  7200,  9000, 10800, 12600, 14400,
       16200, 18000, 19800, 21600, 23400, 25200, 27000, 28800, 30600,
       32400, 34200, 36000, 37800, 39600, 41400, 43200, 45000, 46800,
       48600, 50400, 52200, 54000, 55800, 57600]

B=[555, 666, 0.0, 0.0, 0.0, 0.0, 1, 2, 3,4,5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0, 0.0, 0]

I would like to assign the values from "B" to the elements in the column "value", depending on the index between the intervals indicated in "A". For instance:

  • between 0 and 1800 assign 555 to each value;

  • between 1801, 3600 assign 666 to each value, and so on.

Thank you in advance!

Luca91
  • 541
  • 1
  • 7
  • 19

2 Answers2

1

First, assume A and B are of same size, we can make a table like this:

lookup = pd.DataFrame({'index_col':A, 'B':B})

And let me assume we can make the target dataframe as follows:

df = pd.DataFrame({'index_col':np.arange(57601)})

Now if we merge the two, you will have column B with a lot of NaN for those do not match:

merged_df = df.merge(lookup, how="left", on="index_col")

and then, we can fill all those NaN with "pad":

merged_df = merged_df.fillna(method="pad", axis=0)
adrtam
  • 6,991
  • 2
  • 12
  • 27
0

X = np.zeros(57601) df = pd.DataFrame(X,columns = ['value']) #will create your datarame

for i in range(len(A)-1): df['value'][A[i]:A[i+1]+1] = float(B[i]) # iterating over every range in the A array and assigning values to the dataframe in that range from the B array.

Gopal Chitalia
  • 430
  • 4
  • 18