【问题标题】:keep dataframe numeric after concatenation连接后保持数据帧数字
【发布时间】:2017-10-26 08:34:45
【问题描述】:

有没有办法在连接数字数据框和空数据框后保持结果数据框的数字?

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 和数据框数字

【问题讨论】:

    标签: pandas numpy dataframe concatenation


    【解决方案1】:

    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 转换为float

    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 错误,这些元素实际上是float 所以为什么他们有object dtype 不正确IMO +1
    猜你喜欢
    • 2018-08-09
    • 2017-09-28
    • 1970-01-01
    • 2021-10-10
    • 2013-09-10
    • 1970-01-01
    • 2021-05-05
    • 2022-01-07
    • 1970-01-01
    相关资源
    最近更新 更多