使用float类型的NaN创建空的大 pandas DataFrame的优雅方式 [英] Elegant way to create empty pandas DataFrame with NaN of type float

查看:324
本文介绍了使用float类型的NaN创建空的大 pandas DataFrame的优雅方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个充满NaNs的Pandas DataFrame。在我的研究中,我发现答案

  import pandas as pd 

df = pd.DataFrame(index = range(0,4),columns = [ 'A'])

此代码导致填充了类型对象的NaN的DataFrame。所以他们以后不能使用,例如使用 interpolate()方法。因此,我用这个复杂的代码创建了DataFrame(灵感来自于这个答案):

  import pandas as pd 
import numpy as np

dummyarray = np.empty((4,1))
dummyarray [:] = np.nan

df = pd.DataFrame(dummyarray)

这导致一个DataFrame填充了类型float的NaN,所以它可以在以后使用 interpolate()。是否有更优雅的方式来创建相同的结果?

解决方案

只需将所需的代理作为标量的第一个参数传递, code> 0 , math.inf 或在这种情况下, np.nan 。然后,构造函数将值数组初始化为 index 指定的大小:

 >>> df = pd.DataFrame(np.nan,index = [0,1,2,3],columns = ['A'])
>>> df.dtypes
一个float64
dtype:对象


I want to create a Pandas DataFrame filled with NaNs. During my research I found an answer:

import pandas as pd

df = pd.DataFrame(index=range(0,4),columns=['A'])

This code results in a DataFrame filled with NaNs of type "object". So they cannot be used later on for example with the interpolate() method. Therefore, I created the DataFrame with this complicated code (inspired by this answer):

import pandas as pd
import numpy as np

dummyarray = np.empty((4,1))
dummyarray[:] = np.nan

df = pd.DataFrame(dummyarray)

This results in a DataFrame filled with NaN of type "float", so it can be used later on with interpolate(). Is there a more elegant way to create the same result?

解决方案

Simply pass the desired representative as a scalar first argument, like 0, math.inf or, in this case, np.nan. The constructor then initializes the value array to the size specified by index and columns:

 >>> df = pd.DataFrame(np.nan, index=[0,1,2,3], columns=['A'])
 >>> df.dtypes
 A    float64
 dtype: object

这篇关于使用float类型的NaN创建空的大 pandas DataFrame的优雅方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆