将一列字符串转换为 pandas 列表

2022-01-19 00:00:00 python pandas list string tuples

问题描述

我对 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',')']

你知道怎么做吗?

谢谢.


解决方案

你可以使用 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)))

相关文章