Replace NaN value with array in dataframe

Viewed 295

I'm trying to replace all NaN values in a dataframe with an array [NaN, NaN, NaN] instead. But the normal replace methods (df.replace) don't work because to_replace and value are not the same size.

Thanks in advance :)

2 Answers

I figured something, that should work:

import pandas as pd
import numpy as np

# Sample df with a NaN in column "y"
df = pd.DataFrame({"y": np.NaN, "x": ["Some Value"]})

# Get the nans
isna = df['y'].isna()

# Replace with series with list of (3) nans
df.loc[isna, 'y'] = pd.Series([[np.NaN, np.NaN, np.NaN]] * isna.sum()).values

print(df)

Mainly taken from: https://stackoverflow.com/a/61944174/5635941

Related