【问题标题】:Delete last element from lists in column of data frame based on other column value根据其他列值从数据框列中的列表中删除最后一个元素
【发布时间】:2021-10-27 03:18:26
【问题描述】:

我有一个这样的数据框 df:

 col1  col2 col3               col4                col5      
  Type Key Date first found    Date last found     Images
0  A     1 2020-08-11 07:28:18 2020-08-11 07:28:18 ['image1', 'image2, 'image3']
1  A     2 2020-08-11 07:28:18 2020-08-12 07:28:18 ['image1', 'image2, 'image3']
2  B     3 2020-08-11 07:28:18 2020-08-13 07:28:18 ['image1', 'image2, 'image3']
3  B     4 2020-08-11 07:28:18 2020-08-13 07:28:18 ['image1', 'image2, 'image3']
4  C     5 2020-08-11 07:28:18 2020-08-13 07:28:18 ['image1', 'image2, 'image3']

如果类型为“A”,我想做的是删除最后一个元素“image3”。预期结果:

 col1  col2 col3               col4                col5      
  Type Key Date first found    Date last found     Images
0  A     1 2020-08-11 07:28:18 2020-08-11 07:28:18 ['image1', 'image2]
1  A     2 2020-08-11 07:28:18 2020-08-12 07:28:18 ['image1', 'image2]
2  B     3 2020-08-11 07:28:18 2020-08-13 07:28:18 ['image1', 'image2, 'image3']
3  B     4 2020-08-11 07:28:18 2020-08-13 07:28:18 ['image1', 'image2, 'image3']
4  C     5 2020-08-11 07:28:18 2020-08-13 07:28:18 ['image1', 'image2, 'image3']

我试过没有成功:

del df.loc[df["Type"] == 'A']['Images'][:-1]

df.loc[df["Type"] == 'A']['Images'] = df.loc[df["Type"] == 'A']['Images'].pop()

【问题讨论】:

    标签: python-3.x pandas list dataframe


    【解决方案1】:

    尝试使用str访问器:

    df.loc[df["Type"] == 'A', 'Images'] = df['Images'].str[:-1]
    

    【讨论】:

    • 这是正确的方法,但我认为您不需要使用右侧的 loc:df.loc[df["Type"] == 'A', 'Images'] = df['Images'].str[:-1]。不确定这两个版本是否有速度优势。
    • @SimeonSimeonov 如果可行,请接受并投票 :)
    【解决方案2】:

    为了速度最好的是两边都使用掩码(仅用于处理过滤的行,而不是像另一个答案那样处理所有行)并在变量中防止双重比较,因为 select 用于 str 与 iterables 一起使用,所以这里使用 @987654322 @s:

    mask = df["Type"] == 'A'
    df.loc[mask, 'Images'] = df.loc[mask, 'Images'].str[:-1]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 2015-09-20
      • 2022-08-18
      • 1970-01-01
      • 2018-09-14
      • 2021-03-17
      相关资源
      最近更新 更多