gpt4 book ai didi

python - astype 是否编辑原始数据框?

转载 作者:行者123 更新时间:2023-12-05 03:56:26 26 4
gpt4 key购买 nike

我有一个简单的数据框 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 的数据类型没有改变?

最佳答案

根据 documentation astype 返回一个副本,因此您可以这样做:

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

或者,你也可以这样做:

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

关于python - astype 是否编辑原始数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59313259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com