如何对列值进行操作,列值是一个列表

2024-10-06 08:42:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dataframe,其中一列是list。我要遍历每一行,在列表中找到一个以字母“a”开头的字符串,删除斜杠“/”后面的所有内容

    Index      Entities
     0        ["Apple/1", "Applet/87", "Book/12", "Stable/0"]
     1        ["App/12", "orange/6", "Apples/7", "Stables/0"]

将此数据帧作为输入,我希望新的数据帧如下所示:

      Index      Entities
     0        ["Apple", "Applet", "Book/12", "Stable/0"]
     1        ["App", "orange/6", "Apples", "Stables/0"]

Tags: 数据appappledataframe列表index字母list
1条回答
网友
1楼 · 发布于 2024-10-06 08:42:27

IIUC

[[y.split('/', 1)[0] if y.startswith('A') else y for y in row] for row in df.Entities]

[['Apple', 'Applet', 'Book/12', 'Stable/0'],
 ['App', 'orange/6', 'Apples', 'Stables/0']]

df.assign(
    Entities=[
        [y.split('/', 1)[0] if y.startswith('A') else y
         for y in row] for row in df.Entities
    ]
)

   Index                            Entities
0      0  [Apple, Applet, Book/12, Stable/0]
1      1  [App, orange/6, Apples, Stables/0]

相关问题 更多 >