【问题标题】:Convert to executable values in dictionary python转换为字典python中的可执行值
【发布时间】:2020-10-06 02:44:11
【问题描述】:

我有一本名为 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 中?

【问题讨论】:

  • 不要在字符串中传递代码并执行它。而是传递一个函数对象并调用它。
  • stackoverflow.com/questions/701802/… 这个答案可能会有所帮助
  • 若要扩展@alaniwi 的评论,请删除().column_types = {'A': pa.int32} 等。
  • @DivyangVashi 这不是他想使用exec 函数的情况。
  • @Axe319 我无法移除大括号。因为 int32 和 string 是 pyarrow 的函数。

标签: python python-3.x string pyarrow


【解决方案1】:

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

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

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

【讨论】:

  • 问题是我以编程方式生成此列类型。像下面 column_types['A'] = 'pa.'+datatype+'()' 通过迭代 for 循环
【解决方案2】:

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

【讨论】:

  • 问题是我以编程方式生成此列类型。像下面 column_types['A'] = 'pa.'+datatype+'()' 通过迭代 for 循环
  • 好的,抱歉。我已经更新了答案。检查并告诉我这是否适合你。
猜你喜欢
  • 2011-03-13
  • 2022-11-14
  • 2013-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 2016-10-16
相关资源
最近更新 更多