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,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01