首页 > 解决方案 > 转换为字典python中的可执行值

问题描述

我有一本名为 column_types 的字典,其值如下。

column_types = {'A': 'pa.int32()',
                'B': 'pa.string()'
               }

我想将字典传递给 pyarrow 读取 csv 函数,如下所示

from pyarrow import csv
table = csv.read_csv(file_name,
                     convert_options=csv.ConvertOptions(column_types=column_types)
                     )

但它给出了一个错误,因为字典中的值是一个字符串。以下语句将毫无问题地工作。

from pyarrow import csv
table = csv.read_csv(file_name, convert_options=csv.ConvertOptions(column_types = {
                  'A':pa.int32(),
                  'B':pa.string()
               }))

如何将字典值更改为可执行语句并将其传递到 csv.ConvertOptions ?

标签: pythonpython-3.xstringpyarrow

解决方案


有两种方法对我有用,您可以同时使用它们,但是我会推荐第二种方法作为第一种使用eval()方法,并且在用户输入情况下使用它是有风险的。如果您不使用用户提供的输入字符串,您也可以使用方法 1。

1) 使用eval()

import pyarrow as pa

column_types={}

column_types['A'] = 'pa.'+'string'+'()'
column_types['B'] = 'pa.'+'int32'+'()'

final_col_types={key:eval(val) for key,val in column_types.items()} # calling eval() to parse each string as a function and creating a new dict containing 'col':function()

from pyarrow import csv
table = csv.read_csv(filename,convert_options=csv.ConvertOptions(column_types=final_col_types))
print(table)

2) 通过创建dict_dtypes包含特定字符串的可调用函数名称的主字典。并进一步dict_dtypes用于将字符串映射到其相应的函数。

import pyarrow as pa

column_types={}

column_types['A'] = 'pa.'+'string'+'()'
column_types['B'] = 'pa.'+'int32'+'()'

dict_dtypes={'pa.string()':pa.string(),'pa.int32()':pa.int32()} # master dict containing callable function for a string
final_col_types={key:dict_dtypes[val] for key,val in column_types.items() } # final column_types dictionary created after mapping master dict and the column_types dict

from pyarrow import csv
table = csv.read_csv(filename,convert_options=csv.ConvertOptions(column_types=final_col_types))
print(table)

推荐阅读