如何更改字符串以在 pandas 数据框中列出?

发布于 2025-01-09 03:36:17 字数 256 浏览 2 评论 0原文

我有一个数据框,其中一列有这样的行:

'["user1", "user2" ... ]'

我希望它看起来像这样:

["user1", "user2" ... ]

我想使用 strip() 这样做,但我不知道如何在大括号中写“ ' ”。

df.col =  df.col.str.strip("")

请帮忙。

I have data frame where one column has rows like this:

'["user1", "user2" ... ]'

and I want it to look like this:

["user1", "user2" ... ]

I want to do it this way, using strip(), but I do not know how to write " ' " in brancets.

df.col =  df.col.str.strip("")

Kindly help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温暖的光 2025-01-16 03:36:17

您可以使用eval函数来实现这一点。给定一个字符串,eval 将其解析为 python 表达式。

示例:

>>> str_items = '["user1", "user2"]'
>>> items = eval(str_items)
>>> type(items)
<class 'list'>

从示例中我们可以看到字符串表达式被转换为python列表。

要将 eval 应用于数据框列中的所有项目,我们可以使用 apply 函数。

>>> import pandas as pd
>>> frame = pd.DataFrame()
>>> frame["items"] = [ '["user1", "user2"]', '["user1", "user2"]']

现在我已经构建了一个与您类似的数据框。唯一剩下的就是我们需要将框架列中的所有项目转换为列表。

>>> frame["items"] = frame["items"].apply(eval)
>>> type(frame['items'][0])
<class 'list'>

You can use eval function to achieve this. Given a string, eval parses it to python expression.

Example:

>>> str_items = '["user1", "user2"]'
>>> items = eval(str_items)
>>> type(items)
<class 'list'>

From the example we can see that the string expression is converted to python list.

To apply eval to all items in column of a data frame we can use apply function.

>>> import pandas as pd
>>> frame = pd.DataFrame()
>>> frame["items"] = [ '["user1", "user2"]', '["user1", "user2"]']

Now I have constructed a data frame similar to yours. Only thing remaining is that we need to convert all items in frame column to list.

>>> frame["items"] = frame["items"].apply(eval)
>>> type(frame['items'][0])
<class 'list'>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文