使用float类型的NaN创建空的大 pandas DataFrame的优雅方式 [英] Elegant way to create empty pandas DataFrame with NaN of type float
问题描述
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屋!