将一列字符串转换为 pandas 列表 [英] Convert a columns of string to list in pandas

查看:42
本文介绍了将一列字符串转换为 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',')']

你知道怎么做吗?

谢谢.

推荐答案

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆