从数组中删除包含内容的数据帧行

2024-04-23 09:13:45 发布

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

我有一个很大的数据帧(~1百万行),我需要根据唯一标识符Trade\u Id删除一些行。我在另一个名为tib的数据帧变量上有这些行的内容(在我的测试数据库上是45000行)。我的方法是这个

lentib=len(tib)
for i in range(0,lentib,1): # VERY SLOW
    dat=dat[dat.Trade_Id!=tib.Trade_Id[i]]

但问题是它非常慢,而且执行dat[dat.Trade_Id!=tib.Trade_Id]不起作用。你知道吗

为了提高计算效率,有人有更好的想法吗?我有其他像这样的数据库工作,我不想两天计算这个。你知道吗


Tags: 数据方法inid数据库内容forlen
1条回答
网友
1楼 · 发布于 2024-04-23 09:13:45

使用^{}和否定运算符~将它们过滤掉:

dat=dat[~dat['Trade_Id']isin(tib)]

^{}将生成一个布尔掩码,您可以使用~反转它。这将删除包含id的行

示例:

In [127]:
df = pd.DataFrame({'col1':np.arange(10)})
df

Out[127]:
   col1
0     0
1     1
2     2
3     3
4     4
5     5
6     6
7     7
8     8
9     9

In [128]:    
df[~df['col1'].isin([2,5,8])]

Out[128]:
   col1
0     0
1     1
3     3
4     4
6     6
7     7
9     9

面具看起来像这样:

In [129]:
df['col1'].isin([2,5,8])

Out[129]:
0    False
1    False
2     True
3    False
4    False
5     True
6    False
7    False
8     True
9    False
Name: col1, dtype: bool

相关问题 更多 >