[英]Initialize a Pandas DataFrame with a fill value other than NaN
Suppose I initialize an 'empty' DataFrame as follows: 假设我初始化一个“空” DataFrame,如下所示:
import pandas as pd
import numpy as np
df = pd.DataFrame(index=list('AB'), columns=list('CD'))
The resulting df
has the form 生成的df
具有以下形式
C D
A NaN NaN
B NaN NaN
Is there a pythonic way to replace the NaN
s with some other value, say, -np.inf
? 是否有Python方式将NaN
替换为其他值,例如-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? 也许还有更简洁的方法?
pass scalar value as data
param, this will set all elements to the same value: 将标量值作为data
参数传递,这会将所有元素设置为相同的值:
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. 文档显示, data
参数可以接受常量(标量值)以及类似数组的结构和字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.