Pandas 2.0+如何用astype()将datetime、category转为PyArrow类型?
在Pandas 2.0+中转换为PyArrow的timestamp和dictionary类型
针对你提出的两种PyArrow类型转换需求,以下是具体实现方式:
1. datetime 转 PyArrow timestamp
可以直接使用astype('timestamp[ns][pyarrow]')完成转换,其中ns代表纳秒精度,根据实际需求可替换为ms(毫秒)、us(微秒)等其他时间精度。
如果原列是**字符串类型(object)**的日期,建议先通过pd.to_datetime转为datetime类型后再转PyArrow格式,也可以直接在pd.to_datetime中指定dtype参数一步完成:
# 方式1:先转datetime再转PyArrow timestamp df['col_date'] = pd.to_datetime(df['col_date']).astype('timestamp[ns][pyarrow]') # 方式2:直接转成PyArrow timestamp df['col_date'] = pd.to_datetime(df['col_date'], dtype='timestamp[ns][pyarrow]')
如果原列已经是Pandas的datetime64[ns]类型,直接转换即可:
df['col_date'] = df['col_date'].astype('timestamp[ns][pyarrow]')
2. category 转 PyArrow dictionary
PyArrow的dictionary类型对应Pandas中的category[pyarrow]类型,直接使用该类型字符串即可完成转换:
# 将Pandas category转为PyArrow dictionary类型 df['col_dictionary'] = df['col_dictionary'].astype('category[pyarrow]')
如果需要明确指定字典的键类型(比如字符串键),可以使用完整的类型标识:
df['col_dictionary'] = df['col_dictionary'].astype('dictionary[string][pyarrow]')
完整示例
以下是包含所有类型转换的完整代码示例:
import pandas as pd # 创建测试DataFrame df = pd.DataFrame({ 'col_int': [1, 2, 3], 'col_float': [1.1, 2.2, 3.3], 'col_string': ['a', 'b', 'c'], 'col_date': pd.date_range('2023-01-01', periods=3), 'col_category': pd.Categorical(['x', 'y', 'x']) }) # 转换为PyArrow类型 df['col_int'] = df['col_int'].astype('int8[pyarrow]') df['col_float'] = df['col_float'].astype('float32[pyarrow]') df['col_string'] = df['col_string'].astype('string[pyarrow]') df['col_date'] = df['col_date'].astype('timestamp[ns][pyarrow]') df['col_category'] = df['col_category'].astype('category[pyarrow]') # 查看转换后的类型 print(df.dtypes)
输出的dtypes会显示各列对应的PyArrow类型:
col_int int8[pyarrow] col_float float32[pyarrow] col_string string[pyarrow] col_date timestamp[ns][pyarrow] col_category category[pyarrow] dtype: object
内容的提问来源于stack exchange,提问作者winter
相关产品推荐
相关产品推荐

