python - 创建作为对象存储在单列中的列表列表
问题描述
我将列表存储为数据列中的对象。我需要从这些“列表”中创建一个列表,但它们没有被识别为列表。
我尝试将列转换为列表、连接、创建系列,但结果不被视为列表。
我有的:
code1
Out[83]:
0 ['hair', 'body']
1 ['hair', 'body']
2 ['hair', 'body']
Name: personal_interests, dtype: object
code1.tolist()
Out[79]: ["['hair', 'body']", "['hair', 'body']", "['hair', 'body']"]
我需要的:
example = [['hair', 'body'],
['hair', 'body'],
['hair', 'body']]
example
Out[94]: [['hair', 'body'], ['hair', 'body'], ['hair', 'body']]
解决方案
The following solution evaluates the list inside the string and appends to a new empty list:
from ast import literal_eval
l1 = ["['hair', 'body']", "['hair', 'body']", "['hair', 'body']"]
l2 = []
for i in l1:
l2.append(literal_eval(i))
l2
#[['hair', 'body'], ['hair', 'body'], ['hair', 'body']]
I tried to reproduce the problem by passing the lists as strings instead of pure lists:
df= pd.DataFrame({'a':["['hair', 'body']", "['hair', 'body']"]})
df
a
0 ['hair', 'body']
1 ['hair', 'body']
As you will notice, the elements in the dataframe do not show as strings but as normal lists. When I convert the series to list, the elements are represented as strings, as expected:
df['a'].tolist()
#["['hair', 'body']", "['hair', 'body']"]
So now if we apply
literal_eval on all elements and then convert to list, we get the desired results.
df['a'].apply(literal_eval).tolist()
#[['hair', 'body'], ['hair', 'body']]
推荐阅读
- python - 为什么 Arcgis 将我的地址放在海里?
- javascript - 从外部应用程序打开时的 WebView cookie 生命周期
- spring-boot - Spring Security ROLE_ADMIN 和 ROLE_USER 问题
- android - 如何在 Azure DevOps Pipelines 上指定 Android SDK 构建工具版本
- spring - Thymeleaf/SB 如何将变量从对象传递到链接元素的 href 属性?
- javascript - 具有身份验证的多个 zoid 组件 sdk
- node.js - 登录后如何转到特定的个人资料?
- ios - 如何在视图边框的随机位置上绘制圆圈
- postgresql - postgres 函数返回运算符不存在整数 - 时间戳
- python - Pycharm Python控制台输出与终端python shell输出