当更改特定列的值和/或数据类型时,从Pandas 1.x到2.x会有不同的行为.

例如,在下例中的第e列上:

  • Pandas 1.x:使用pd.to_datetime更新该列将 解析日期并更改其数据类型
  • Pandas 2.x:使用 pd.to_datetime来更新列将解析日期,但 不会更改其数据类型

从Pandas 1.x到2.x的什么变化解释了这种行为?

Example code

import pandas as pd

# Creates example DataFrame
df = pd.DataFrame({
    'a': ['1', '2'],
    'b': ['1.0', '2.0'],
    'c': ['True', 'False'],
    'd': ['2024-03-07', '2024-03-06'],
    'e': ['07/03/2024', '06/03/2024'],
    'f': ['aa', 'bb'],
})

# Changes dtypes of existing columns
df.loc[:, 'a'] = df.a.astype('int')
df.loc[:, 'b'] = df.b.astype('float')
df.loc[:, 'c'] = df.c.astype('bool')

# Parses and changes dates dtypes
df.loc[:, 'd'] = pd.to_datetime(df.d)
df.loc[:, 'e'] = pd.to_datetime(df.e, format='%d/%m/%Y')

# Changes values of existing columns
df.loc[:, 'f'] = df.f + 'cc'

# Creates new column
df.loc[:, 'g'] = [1, 2]

Results in Pandas 1.5.2

In [2]: df
Out[2]: 
   a    b     c          d          e     f  g
0  1  1.0  True 2024-03-07 2024-03-07  aacc  1
1  2  2.0  True 2024-03-06 2024-03-06  bbcc  2

In [3]: df.dtypes
Out[3]: 
a             int64
b           float64
c              bool
d    datetime64[ns]
e    datetime64[ns]
f            object
g             int64
dtype: object

Results in Pandas 2.1.4

In [2]: df
Out[2]: 
   a    b     c                    d                    e     f  g
0  1  1.0  True  2024-03-07 00:00:00  2024-03-07 00:00:00  aacc  1
1  2  2.0  True  2024-03-06 00:00:00  2024-03-06 00:00:00  bbcc  2

In [3]: df.dtypes
Out[3]: 
a    object
b    object
c    object
d    object
e    object
f    object
g     int64
dtype: object

推荐答案

What’s new in 2.0.0 (April 3, 2023)人起:

改变了用df.loc[:, foo] = bardf.iloc[:, foo] = bar设置值的行为,它们现在总是在回落到施法(GH 45333)之前try 就地设定值.

因此,在Pandas 2+中,每当您将值设置为.loc时,它都会try 将它们设置到位.如果成功,它将不会创建新列,并将保留现有列的dtype.

将其与df[foo] = bar进行比较:这将创建一个新列,其中包含从正在设置的值推断出的dtype.当您执行df['d'] = pd.to_datetime(df.d)时也会发生同样的情况,也就是说,即使在Pandas 2+中,它也会创建datetime64[ns]中的dtype的新列.

Python相关问答推荐

运行回文查找器代码时发生错误:[类型错误:builtin_index_or_system对象不可订阅]

使用mySQL的SQlalchemy过滤重叠时间段

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

有没有一种方法可以从python的pussompy比较结果中提取文本?

Pandas—在数据透视表中占总数的百分比

如何使用scipy的curve_fit与约束,其中拟合的曲线总是在观测值之下?

如何使Matplotlib标题以图形为中心,而图例框则以图形为中心

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

Maya Python脚本将纹理应用于所有对象,而不是选定对象

Python—为什么我的代码返回一个TypeError

我对这个简单的异步者的例子有什么错误的理解吗?

freq = inject在pandas中做了什么?''它与freq = D有什么不同?''

504未连接IB API TWS错误—即使API连接显示已接受''

时长超过24小时如何从Excel导入时长数据

PYTHON中的selenium不会打开 chromium URL

Django更新视图未更新

在Pandas 中以十六进制显示/打印列?

FileNotFoundError:[WinError 2]系统找不到指定的文件:在os.listdir中查找扩展名

如何批量训练样本大小为奇数的神经网络?

为什么这个正则表达式没有捕获最后一次输入?