Home > Blockchain >  how to apply a pandas series to a Dataframe?
how to apply a pandas series to a Dataframe?

Time:12-12

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

You can change df's indices to the indices of the true values of indices using the set_index method, then use reindex method to conform df to the indices of indices:

out = df.set_index(indices.index[indices]).reindex(indices.index)

Output:

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

CodePudding user response:

df= [(0, 50) , (1, 57) ,(2, 3) ,(4, 6) ,(5, 8)]
indices =[True, False ,False ,True, False, False, True, True, True, False, False]
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)
  • Related