Convert a columns of string to list in pandas(将一列字符串转换为 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 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将一列字符串转换为 pandas 列表


基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01