【问题标题】:Does astype edit original dataframe?astype 是否编辑原始数据框?
【发布时间】:2021-12-23 11:04:44
【问题描述】:

我有一个简单的数据框 df:

col1 | col2
 7   |  8
 12  |  14

当我通过编写df.dtypes检查df的数据类型时,int64是两列的数据类型。

现在我通过键入来更改 col1 的数据类型

df.astype({'col1': 'float64'}).dtypes

返回

col1    float64
col2      int64
dtype: object

好的,到目前为止一切都很好。所以现在当我仔细检查数据类型是否改变了 df...

df.dtypes

输出是

col1    int64
col2    int64
dtype: object

我认为 astype 会永久更改我原来的 df 的数据类型。所以我在这里很困惑。为什么 df 的数据类型没有变化?

【问题讨论】:

标签: python pandas numpy dataframe


【解决方案1】:

根据documentation astype 返回一个副本,所以你可以这样做:

df = df.astype({'col1': 'float64'})

或者,您也可以这样做:

df.col1 = df.col1.astype('float64')

【讨论】:

  • 复制参数仍然返回一个新的帧而不修改原来的。
  • @cs95 谢谢。固定。
【解决方案2】:

这里的问题是操作不起作用inplace 这就是为什么参数copy 是函数的一部分的原因。

此外,如果您希望更改是永久性的,您需要重新定义您的数据框。

df = df.astype({'col1': 'float64'})

这样当您检查df.dtypes 时,col1 将是浮动的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-11
    • 2010-11-02
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多