python - 使用 NaN 以外的填充值初始化 Pandas DataFrame

标签 python pandas

假设我按如下方式初始化“空”DataFrame:

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

生成的 df 具有以下形式

     C    D
A  NaN  NaN
B  NaN  NaN

是否有一种 pythonic 方法可以将 NaN 替换为其他值,例如 -np.inf?当然,一种方法是简单地将其指定为数据:

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

也许有更简洁的方法?

最佳答案

将标量值作为 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

docs显示 data 参数可以接受常量(标量值)以及类似数组的结构和字典。

关于python - 使用 NaN 以外的填充值初始化 Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38640664/

相关文章:

python - PyQtGraph PlotWidget : how to force each draw (changing range) for "real time" plotting

BLAST比对算法的Python实现?

python - 超出最大递归深度

python - 在两个 python 装饰器之间传递变量

python - 将数据帧旋转到一级/重命名 df.pivot() 输出列

python - 如何在 DataFrame 中连接附近重复的行

python - 跟踪 Dataframe 中的操作

python - 如何使用多处理来加速以下功能?

python - Matplotlib 和 Numpy 与某些 Pandas 函数的兼容性? - 需要整数

python - 列和索引的最大值作为元组