【问题标题】:How to read a list from an excel cell如何从excel单元格中读取列表
【发布时间】:2020-02-17 04:25:45
【问题描述】:

我将一个列表放入一个excel单元格,当我用pandas读取它时,它没有返回一个列表,它返回了一个字符串,有没有我可以得到一个列表作为回报?

例如。 在单元格中:['a', 'b', 'c'] 熊猫的输出:'['a', 'b', 'c']'

这是我的代码:

df = pd.read_excel('example.xlsx', index_col=None, header=None)

print(df.iloc[5, 3])
print(type(df.iloc[5, 3]))
## and the code would return the type of df.iloc[5, 3] is equal to a list

【问题讨论】:

    标签: python excel string pandas list


    【解决方案1】:

    您可以使用eval()。这是一个例子:

    a = "['a', 'b']"
    print(eval(a))
    

    打印出来:

    ['a', 'b']
    

    【讨论】:

      【解决方案2】:

      在 excel 中,列表转换为列表的字符串 repr。

      df = pd.DataFrame({
              'A':list('abcdef'),
               'B':[4,5,4,5,5,4],
               'C':[7,8,9,4,2,3],
               'D':[1,3,5,7,1,['a', 'b', 'c']],
               'E':[5,3,6,9,2,4],
               'F':list('aaabbb')
      })
      
      print(df.iloc[5, 3])
      ['a', 'b', 'c']
      
      df.to_excel('example.xlsx', header=None, index=False)
      
      df = pd.read_excel('example.xlsx', index_col=None, header=None)
      
      print(df.iloc[5, 3])
      ['a', 'b', 'c']
      
      print(type(df.iloc[5, 3]))
      <class 'str'>
      

      因此有必要将其转换为ast.literal_eval 的列表

      import ast
      
      print(ast.literal_eval(df.iloc[5, 3]))
      ['a', 'b', 'c']
      
      print(type(ast.literal_eval(df.iloc[5, 3])))
      <class 'list'>
      

      或者eval,但是it is bad practise,所以不推荐:

      print(eval(df.iloc[5, 3]))
      ['a', 'b', 'c']
      
      print(type(eval(df.iloc[5, 3])))
      <class 'list'>
      

      【讨论】:

      • 感谢您的解决方案!但是请您向我解释一下ast.literal_eval 和普通eval 之间的区别?
      • @Andrew Anjun Hou 检查this post.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多