【问题标题】:Converting a pandas dtype string representation to dict将 pandas dtype 字符串表示形式转换为 dict
【发布时间】:2021-03-10 10:16:17
【问题描述】:

我在尝试将 dtype 表示形式转换为 dict 时遇到问题。 实际上,我通过 API 发送这个字符串,以便在 read_csv 函数中使用它:

MyString='{"dept": str}' # This is received from an API

pd.read_csv(file, dtype=MyString)
--> data type '{"dept": str}' not understood: TypeError

# Then, I tried: 
pd.read_csv(file, dtype=dict(MyString))
--> ValueError: dictionary update sequence element #0 has length 1; 2 is required

# In a desperate move, I did:
pd.read_csv(file, dtype=ast.literal_eval(MyString))
--> ValueError: malformed node or string: <_ast.Name object at 0x7f3527139128>

我缺少什么,请问我该如何实现?来自熊猫文档:

dtype : Type name or dict of column -> type, optional
Data type for data or columns

【问题讨论】:

    标签: python python-3.x pandas dictionary


    【解决方案1】:

    你的字符串包含一个类名,所以不容易解析,不能跟literal_eval,也不能跟json模块。

    我只能想象两种方式

    1. 使用邪恶的eval。如果你确定不会有任何问题,你可以eval字符串

       pd.read_csv(file, dtype=ast.literal_eval(MyString))
      

      由于它允许执行任意代码,这应该只是绝望的方式。但至少它立即起作用。

    2. 解析字符串,将str变成字符串:

      如果来自 API 的字符串不包含错位的逗号、冒号或引号字符,您可以使用:

       dt = {k: v for elt in MyString[1:-1].split(',')
             for k,v in [[i.strip('" ') for i in elt.split(':', 1)]]}
       df = pd.read_csv(io.StringIO(t), dtype=dt)
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 2022-01-19
      • 2018-12-12
      • 2016-06-30
      • 1970-01-01
      • 2012-01-06
      • 2018-01-23
      相关资源
      最近更新 更多