转换为python字典中的可执行值

2024-10-04 03:23:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我想将字典传递给pyarrow read 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


Tags: csvnamefromimportreadstring字典table
2条回答

我们为什么不使用这样的东西:

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

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

有两种方法对我有效,你可以同时使用它们,但是我建议使用第二种方法,因为第一种方法使用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)

相关问题 更多 >