【问题标题】:How to delete group of rows if in certain column value doesn't met the condition?如果某些列值不满足条件,如何删除行组?
【发布时间】:2021-10-20 11:35:27
【问题描述】:

例如,这里是表格(df):

Number Code Action DateTime
7271 1 send 2021-10-20 13:12:18
7271 1 get 2021-10-20 13:12:20
7271 1 take 2021-10-20 13:12:21
7271 1 reply 2021-10-20 13:12:25
7271 1 send: 2021-10-20 13:15:18
7271 1 get 2021-10-20 13:15:20
7271 5 take 2021-10-20 13:15:21
7271 5 reply 2021-10-20 13:15:25

我想删除行组,其中在“操作”列中,字符串“发送”没有“:”(冒号)。 我的意思是,我想要一个表格,其中在“操作”列中,字符串“发送”包含一个冒号以及该行的组。通过行的组,我的意思是具有相同数字和日期时间的行(在某个间隔内)。 此外,数字可以重复,但日期时间不同。 有超过 100 000 个数据。

新表应如下所示:

Number Priority Action DateTime
7271 1 send: 2021-10-20 13:15:18
7271 1 get 2021-10-20 13:15:20
7271 5 take 2021-10-20 13:15:21
7271 5 reply 2021-10-20 13:15:25

P.S:字符串'send'带冒号('send:')表示回复了某个号码的客户端。

【问题讨论】:

  • 我在想:i)创建新列,其中字符串“发送”(无冒号)为真。 ii) 然后删除一行(如果新列为 True)和(如果对应于 True 值的数字在各行中相同)和(如果 DateTime 在 True 值的 2 分钟内)。如果满足这 3 个条件,我将删除该行。有可能吗?

标签: pandas data-analysis


【解决方案1】:

使用布尔掩码:

mask = df.loc[df['Action'].str.startswith('send'), 'Action'] \
         .str.endswith(':').reindex(df.index).ffill()

df = df[mask]
print(df)

# Output:
   Number  Code Action             DateTime
4    7271     1  send:  2021-10-20 13:15:18
5    7271     1    get  2021-10-20 13:15:20
6    7271     5   take  2021-10-20 13:15:21
7    7271     5  reply  2021-10-20 13:15:25

【讨论】:

    【解决方案2】:

    您可以通过Series.str.startswithSeries.cumsum 的累积总和比较send 之后的值创建组,并仅过滤send: 中的Series.isin 中的组:

    m1 = df['Action'].str.startswith('send')
    m2 = df['Action'].eq('send:')
    s = m1.cumsum()
    
    df = df[s.isin(s[m2])]
    print (df)
       Number  Code Action             DateTime
    4    7271     1  send:  2021-10-20 13:15:18
    5    7271     1    get  2021-10-20 13:15:20
    6    7271     5   take  2021-10-20 13:15:21
    7    7271     5  reply  2021-10-20 13:15:25
    

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多