如何操作列值Python的列值

时间:2019-06-28 19:55:30

标签: python pandas dataframe

我有一个数据框,其中一列是列表。我想遍历每一行,并在列表中找到一个以字母“ 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"]

1 个答案:

答案 0 :(得分:2)

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]