Monica
Monica

Reputation: 1070

filling cells in DataFrame

I created the DataFrame and faced a problem:

      r       value    
0    0.8     2.5058
1    0.9    -1.9320
2    1.0    -2.6097
3    1.2    -1.6840
4    1.4    -0.8906
5    0.8     2.6955
6    0.9    -1.9552
7    1.0    -2.6641
8    1.2    -1.7169
9    1.4    -0.9056
...   ...    ...

For r from 0.8 to 1.4, I want to assign the value for r = 1.0. Therefore the desired Dataframe should look like:

   r       value    
0    0.8    -2.6097
1    0.9    -2.6097
2    1.0    -2.6097
3    1.2    -2.6097
4    1.4    -2.6097
5    0.8    -2.6641
6    0.9    -2.6641
7    1.0    -2.6641
8    1.2    -2.6641
9    1.4    -2.6641
...  ...    ....

My first idea wast to create the condition:

np.where(data['r']==1.0, data['value'], 1.0)

but it does not solve my problem.

Upvotes: 2

Views: 131

Answers (2)

Merlin
Merlin

Reputation: 25639

Starting with this:

   r   value
0  0.8 -2.6097
1  0.9 -2.6097
2  1.0 -2.6097
3  1.2 -2.6097
4  1.4 -2.6097
5  0.8 -2.6641
6  0.9 -2.6641
7  1.0 -2.6641
8  1.2 -2.6641
9  1.4 -2.6641


df3['grp']   = (df3['r'] ==.8).cumsum()
grpd         = dict(df3[['grp','value']][df3['r'] == 1].values)
df3["value"] = df3["grp"].map(grpd)
df3          = df3.drop('grp', axis=1)


     r   value
0  0.8 -2.6097
1  0.9 -2.6097
2  1.0 -2.6097
3  1.2 -2.6097
4  1.4 -2.6097
5  0.8 -2.6641
6  0.9 -2.6641
7  1.0 -2.6641
8  1.2 -2.6641
9  1.4 -2.6641

Upvotes: 1

piRSquared
piRSquared

Reputation: 294278

Try this:

def subr(df):
    isone = df.r == 1.0
    if isone.any():
        atone = df.value[isone].iloc[0]
        # Improvement suggested by @root
        df.loc[df.r.between(0.8, 1.4), 'value'] = atone
        # df.loc[(df.r >= .8) & (df.r <= 1.4), 'value'] = atone
    return df

df.groupby((df.r < df.r.shift()).cumsum()).apply(subr)

enter image description here

Upvotes: 1

Related Questions