Home > Net >  Filling a dataframe with values from a Series based on a list of index
Filling a dataframe with values from a Series based on a list of index

Time:11-19

I need to pass values from a pandas Series (val) to a dataframe column ('column_a') at index (indices). How can I do this?

import pandas as pd
import numpy as np

df_test = pd.DataFrame(index=np.arange(4000), columns=np.arange(1))
df_test.columns = ['column_a']
val = pd.Series([0.267, 0.331, 0.486, 0.224, 0.334])
indices = pd.Series([2, 7, 9, 12, 70])

CodePudding user response:

Let's use pandas intrinsic data alignment by setting the index of val then assign that pd.Series to the dataframe column.

df_test.columns = ['column_a']
val = pd.Series([0.267, 0.331, 0.486, 0.224, 0.334])
indices = pd.Series([2, 7, 9, 12, 70])

df_test['column_a'] = val.set_axis(indices)

print(df_test[df_test['column_a'].notna()])

Output (print only values in df_test that are not null):

    column_a
2      0.267
7      0.331
9      0.486
12     0.224
70     0.334

CodePudding user response:

Use pandas's loc method:

df_test.loc[indices.to_numpy(), 'column_a']=val.to_numpy()

  • Related