python - 转换为字典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 ?
解决方案
有两种方法对我有用,您可以同时使用它们,但是我会推荐第二种方法作为第一种使用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)
推荐阅读
- python - 如何通过在python中迭代句子中的单词来创建表格?
- firebase - Django rest 不调用自定义身份验证后端?
- python - 如何使用 Yolo 对象检测在推理上平铺图像
- python - 通过WSL在windows中安装像bowtie2这样的生物信息学包
- javascript - div 的样式为 100vh,带有内部滚动,因此当 **滚动期间视口中的每个 **section-wrapper** 时,我需要为每个 **section-wrapper** 切换类**
- php - 使用getImage().'-1.jpg'?> 从数据库中获取图像名称
- curl - -bash:意外标记“crontab”附近的语法错误
- android - 如果文本超出屏幕框架,是否有可能更改 textView 的位置?
- python - sh:Script.py:找不到命令
- mysql - 不包含用于 linq 的位置的定义