更新: 在 Polars 中不再出现这种情况。结果是预期的
date
类型列。
为什么模式规范没有影响?出生日期仍然是字符串格式,为什么?
import polars as pl
# Create a dictionary with some dummy data
data = {
'Age': [28, 32, 24, 45, 29],
'Date of Birth': ['1995-03-15', '1989-08-22', '1999-11-05', '1978-02-10', '1994-06-07'],
'City': ['New York', 'San Francisco', 'London', 'Tokyo', 'Sydney'],
}
dtypes = {
'Age': pl.Int64,
'Date of Birth': pl.Date,
'City': pl.String
}
# Create the DataFrame with specified data types
df_listing_data = pl.DataFrame(data, schema=dtypes)
出生日期仍然是字符串格式,为什么?
# shape: (5, 3)
# ┌─────┬───────────────┬───────────────┐
# │ Age ┆ Date of Birth ┆ City │
# │ --- ┆ --- ┆ --- │
# │ i64 ┆ str ┆ str │
您没有给它日期对象,而是给它一个字符串列表。它不会猜测如何解析它们。实际上,我很惊讶它不会因向其提供不符合指定数据类型的数据而引发错误。我想说这是一个 bug 但该 bug 的解决方案是你会得到一个错误,而不是一个 df 具有错误的 dtype。要获取日期,您需要给它一个日期对象列表,或者告诉它如何在创建 df 后将字符串解析为日期,或者给它一个日期类型的 Series。
你可以做
from datetime import datetime
data = {
'Age': [28, 32, 24, 45, 29],
'Date of Birth': [datetime.strptime(x, "%Y-%m-%d").date() for x in ['1995-03-15', '1989-08-22', '1999-11-05', '1978-02-10', '1994-06-07']],
'City': ['New York', 'San Francisco', 'London', 'Tokyo', 'Sydney'],
}
dtypes = {
'Age': pl.Int64,
'Date of Birth': pl.Date,
'City': pl.Utf8
}
# Create the DataFrame with specified data types
df_listing_data = pl.DataFrame(data, schema=dtypes)
或
data = {
'Age': [28, 32, 24, 45, 29],
'Date of Birth': ['1995-03-15', '1989-08-22', '1999-11-05', '1978-02-10', '1994-06-07'],
'City': ['New York', 'San Francisco', 'London', 'Tokyo', 'Sydney'],
}
dtypes = {
'Age': pl.Int64,
'Date of Birth': pl.Date,
'City': pl.Utf8
}
# Create the DataFrame with specified data types
df_listing_data = pl.DataFrame(data, schema=dtypes).with_columns(
pl.col('Date of Birth').str.strptime(pl.Date(), "%Y-%m-%d"))
或
data = {
'Age': [28, 32, 24, 45, 29],
'Date of Birth': pl.Series(['1995-03-15', '1989-08-22', '1999-11-05', '1978-02-10', '1994-06-07']).str.strptime(pl.Date(), "%Y-%m-%d"),
'City': ['New York', 'San Francisco', 'London', 'Tokyo', 'Sydney'],
}
dtypes = {
'Age': pl.Int64,
'Date of Birth': pl.Date,
'City': pl.Utf8
}
# Create the DataFrame with specified data types
df_listing_data = pl.DataFrame(data, schema=dtypes)