3

Suppose I initialize an 'empty' DataFrame as follows:

import pandas as pd
import numpy as np
df = pd.DataFrame(index=list('AB'), columns=list('CD'))

The resulting df has the form

     C    D
A  NaN  NaN
B  NaN  NaN

Is there a pythonic way to replace the NaNs with some other value, say, -np.inf? Of course, one way to do it is simply to specify it as data:

df = pd.DataFrame(data=np.ones((2,2))*(-np.inf), index=list('AB'), columns=list('CD'))

Perhaps there a more succinct way?

Kurt Peek
  • 52,165
  • 91
  • 301
  • 526
  • Duplicate of [https://stackoverflow.com/questions/30053329/elegant-way-to-create-empty-pandas-dataframe-with-nan-of-type-float](Elegant way to create empty pandas DataFrame with NaN of type float), you can initialize with `pd.DataFrame(data=...` whatever you like. – smci Jun 03 '18 at 08:17

1 Answers1

4

pass scalar value as data param, this will set all elements to the same value:

In [181]:
df = pd.DataFrame(index=list('AB'), columns=list('CD'), data=-np.inf)
df

Out[181]:
     C    D
A -inf -inf
B -inf -inf

The docs show that data param can accept constants (scalar values) as well as array-like structures and dicts.

EdChum
  • 376,765
  • 198
  • 813
  • 562