将一列字符串转换为以pandas列出 [英] Convert a columns of string to list in pandas
问题描述
我对pandas数据框中的某一列的类型有疑问.基本上,该列以字符串形式保存在csv文件中,我想将其用作元组,以便能够将其转换为数字列表.接下来是一个非常简单的csv:
I have a problem with the type of one of my column in a pandas dataframe. Basically the column is saved in a csv file as a string, and I wanna use it as a tuple to be able to convert it in a list of numbers. Following there is a very simple csv:
ID,LABELS
1,"(1.0,2.0,2.0,3.0,3.0,1.0,4.0)"
2,"(1.0,2.0,2.0,3.0,3.0,1.0,4.0)"
如果使用函数"read_csv"加载它,则会得到字符串列表.我试图转换为列表,但是得到了字符串的列表版本:
If a load it with the function "read_csv" I get a list of strings. I have tried to convert to a list, but I get the list version of a string:
df.LABELS.apply(lambda x: list(x))
返回:
['(','1','.','0',.,.,.,.,.,'4','.','0',')']
关于如何做到这一点的任何想法?
Any idea on how to be able to do it?
谢谢.
推荐答案
您可以使用ast.literal_eval
,这将为您提供一个元组:
You can use ast.literal_eval
, which will give you a tuple:
import ast
df.LABELS = df.LABELS.apply(ast.literal_eval)
如果您想要列表,请使用:
If you do want a list, use:
df.LABELS.apply(lambda s: list(ast.literal_eval(s)))
这篇关于将一列字符串转换为以pandas列出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!