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 列表
基础教程推荐
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
