【发布时间】:2022-06-15 00:03:09
【问题描述】:
我有一个 Pandas 数据框,其中有一列包含字典值。我想使用 DuckDB 查询此数据帧并将结果转换为另一个数据帧,并在整个查询中保留类型。
DuckDB 具有MAP 数据类型,看起来与字典非常匹配,但是在选择列时,它会变成VARCHAR,如果我转换回数据框,则会产生字符串类型的列。
在生成新数据帧时,是否有某种方法可以保留类型,或者至少有一种将字符串转换回字典的好方法?
>>> # Create a dataframe with a column containing a dictionary
>>> df = pd.DataFrame([[{'some': 'dict', 'with': 'stuff'}]], columns=['mycol'])
>>> df
mycol
0 {'some': 'dict', 'with': 'stuff'}
>>> type(df['mycol'][0])
<class 'dict'>
>>> # Select that column using DuckDB - it becomes a VARCHAR
>>> duckdb.query('select mycol from df')
---------------------
-- Expression Tree --
---------------------
Subquery
---------------------
-- Result Columns --
---------------------
- mycol (VARCHAR)
---------------------
-- Result Preview --
---------------------
mycol
VARCHAR
[ Rows: 1]
{'some': 'dict', 'with': 'stuff'}
>>> # Converting the query result to another dataframe results in a string-type column
>>> df2 = duckdb.query('select mycol from df').to_df()
>>> df2
mycol
0 {'some': 'dict', 'with': 'stuff'}
>>> type(df2['mycol'][0])
<class 'str'>
>>> # An explicit cast to MAP doesn't work
>>> duckdb.query('select CAST(mycol as MAP(VARCHAR, VARCHAR)) from df')
---------------------
-- Expression Tree --
---------------------
Subquery
---------------------
-- Result Columns --
---------------------
- CAST(mycol AS MAP<VARCHAR, VARCHAR>) (MAP<VARCHAR, VARCHAR>)
---------------------
-- Result Preview --
---------------------
Conversion Error: Conversion Error: Unimplemented type for cast (VARCHAR -> MAP<VARCHAR, VARCHAR>)
【问题讨论】:
标签: python pandas dataframe duckdb