Pandas 连接后保持数据帧为数字
在连接数字数据帧和空数据帧后,是否有方法保持结果数据帧为数字Pandas 连接后保持数据帧为数字,pandas,numpy,dataframe,concatenation,Pandas,Numpy,Dataframe,Concatenation,在连接数字数据帧和空数据帧后,是否有方法保持结果数据帧为数字 df1 = pd.DataFrame(data=[[1,2],[3,4]], columns=['a','b'], index=[0,1]) df1.dtypes Out[25]: a int64 b int64 dtype: object df2 = pd.DataFrame(columns=['c','d']) df2.dtypes Out[27]: c object d object dtype:
df1 = pd.DataFrame(data=[[1,2],[3,4]], columns=['a','b'], index=[0,1])
df1.dtypes
Out[25]:
a int64
b int64
dtype: object
df2 = pd.DataFrame(columns=['c','d'])
df2.dtypes
Out[27]:
c object
d object
dtype: object
df = pd.concat([df1,df2], axis = 1)
df
Out[28]:
a b c d
0 1 2 NaN NaN
1 3 4 NaN NaN
我希望添加的行是np.nan,并且数据帧数值将
dtype
参数设置为float
:
df2 = pd.DataFrame(columns=['c','d'], dtype=float)
df = pd.concat([df1,df2], axis = 1)
print (df)
a b c d
0 1 2 NaN NaN
1 3 4 NaN NaN
print (df.dtypes)
a int64
b int64
c float64
d float64
dtype: object
df = pd.concat([df1,df2.astype(float)], axis = 1)
print (df)
a b c d
0 1 2 NaN NaN
1 3 4 NaN NaN
print (df.dtypes)
a int64
b int64
c float64
d float64
dtype: object
或将空df
转换为float
:
df2 = pd.DataFrame(columns=['c','d'], dtype=float)
df = pd.concat([df1,df2], axis = 1)
print (df)
a b c d
0 1 2 NaN NaN
1 3 4 NaN NaN
print (df.dtypes)
a int64
b int64
c float64
d float64
dtype: object
df = pd.concat([df1,df2.astype(float)], axis = 1)
print (df)
a b c d
0 1 2 NaN NaN
1 3 4 NaN NaN
print (df.dtypes)
a int64
b int64
c float64
d float64
dtype: object
这看起来像是一个
pandas
bug,这些元素实际上是float
所以为什么它们有object
dtype是不正确的IMO+1