how to apply a pandas series to a Dataframe?

Viewed 81

if i had a Dataframe like this

df=
   value
0    50
1    57
2    3
4    6
5    8

and a boolean series like this

indices =
True
False
False
True
False
False
True
True
True
False
False

how do i apply this boolean series to the Dataframe and make it like this

df=
   value
0    50
1    NAN
2    NAN
3    57
4    NAN
5    NAN
6    3
7    6
8    8
9    NAN
10   NAN
4 Answers

Another solution could be:

import pandas as pd
import numpy as np

df = pd.DataFrame({"value":[1.3, 2.0]})
indeces = [True, False, True]

pd.DataFrame([df.at[y-1, "value"] if x else np.nan for x, y in zip(indeces,np.cumsum(indeces))], columns=["value"])

OUTPUT

   value
0    1.3
1    NaN
2    2.0

Important: remember to reset the indeces of your dataframe in case they are not consecutive and starting from 0

Convert indices to frame:

indices = indices.to_frame(name='bools')

Create empty column:

indices['value'] = np.nan

Replace matching boolean points:

indices.loc[indices['bools'], 'value'] = df.value.array

indices
     bools  value
0    True   50.0
1   False    NaN
2   False    NaN
3    True   57.0
4   False    NaN
5   False    NaN
6    True    3.0
7    True    6.0
8    True    8.0
9   False    NaN
10  False    NaN

You can subsequently drop the bools column.

Let us try with reindex

m = indices
df.set_axis(m.index[m]).reindex(m.index)

   value
0     50
1    NaN
2    NaN
3     57
4    NaN
5    NaN
6      3
7      6
8      8
9    NaN
10   NaN

I create a list of tuples for df:

df= [(0, 50) , (1, 57) ,(2, 3) ,(4, 6) ,(5, 8)]

Also,I create a list of indices:

indices =[True, False, False, True, False, False, True, True, True, False, False]

I defined the result as a list for saving the result:

result=[]
n =len(indices)
df_ix=0

for i in range(n):
    if indices[i]:
        result.append((i, df[df_ix][1]))
        df_ix+=1
    else:
        result.append((i, "NAN"))
print(result)

Output:

[(0, 50), (1, 'NAN'), (2, 'NAN'), (3, 57), (4, 'NAN'), (5, 'NAN'), (6, 3), (7, 6), (8, 8), (9, 'NAN'), (10, 'NAN')]
Related