需求
我正在尝试将一个dataframe导出到Parquet文件,这个文件稍后将被不是Python或Pandas的东西所消耗。(Azure资料厂)
当我在流的后面摄入Parquet文件时,它无法识别datetime64[ns]。我宁愿使用“香草”Python datetime.datetime。
问题
但我无法做到这一点。问题是,Pandas正在强制任何“类似于日期时间的对象在返回数据或系列后进入datetime64[ns]”。
小例子
例如,假设带有"timestamp"列的虹膜数据集:
>>> df.head()
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) class timestamp
0 5.1 3.5 1.4 0.2 setosa 2021-02-19 15:07:24.719272
1 4.9 3.0 1.4 0.2 setosa 2021-02-19 15:07:24.719272
2 4.7 3.2 1.3 0.2 setosa 2021-02-19 15:07:24.719272
3 4.6 3.1 1.5 0.2 setosa 2021-02-19 15:07:24.719272
4 5.0 3.6 1.4 0.2 setosa 2021-02-19 15:07:24.719272
>>> df.dtypes
sepal length (cm) float64
sepal width (cm) float64
petal length (cm) float64
petal width (cm) float64
class category
timestamp datetime64[ns]
dtype: object我可以将一个值转换为“普通Python日期时间”:
>>> df.timestamp[1]
Timestamp('2021-02-19 15:07:24.719272')
>>> type(df.timestamp[1])
<class 'pandas._libs.tslibs.timestamps.Timestamp'>
>>> df.timestamp[1].to_pydatetime()
datetime.datetime(2021, 2, 19, 15, 7, 24, 719272)
>>> type(df.timestamp[1].to_pydatetime())
<class 'datetime.datetime'>但是,当我转换整个列/系列时,我不能将它“保存”在这种类型中:
>>> df['ts2'] = df.timestamp.apply(lambda x: x.to_pydatetime())
>>> df.dtypes
sepal length (cm) float64
sepal width (cm) float64
petal length (cm) float64
petal width (cm) float64
class category
timestamp datetime64[ns]
ts2 datetime64[ns]可能的解决办法
我想看看是否有什么我可以做的,“哑巴”的数据栏,并使它的日期时间不那么精确。但我什么也看不见。我也看不到在通过df.to_parquet()方法导出时指定列数据类型的选项。
是否有一种方法可以在Pandas中创建普通的Python datetime.datetime列(而不是Numpy/Pandas datetime65[ns]列)?
发布于 2021-02-19 16:15:40
使用dtype='object'时尝试强制使用to_pydatetime
df['ts'] = pd.Series(df.timestamp.dt.to_pydatetime(),dtype='object')
df.loc[0,'ts']输出:
datetime.datetime(2021, 2, 19, 15, 7, 24, 719272)https://stackoverflow.com/questions/66279478
复制相似问题