我有一个包含列的数据框A,B,C.我有一个像元组的列表[(x1,y1), (x2,y2), ...].我想删除满足以下条件的所有行:
(B=x1 && C=y1) | (B=x2 && C=y2) | ...我怎么能在熊猫中做到这一点?我想使用该isin函数,但不确定是否可以,因为我的列表有元组.我可以这样做:
for x,y in tuples:
df = df.drop(df[df.B==x && df.C==y].index)
Run Code Online (Sandbox Code Playgroud)
也许有一种更简单的方法.
使用pandas索引
df.set_index(list('BC')).drop(tuples, errors='ignore').reset_index()
Run Code Online (Sandbox Code Playgroud)
def linear_indexing_based(df, tuples):
idx = np.array(tuples)
BC_arr = df[['B','C']].values
shp = np.maximum(BC_arr.max(0)+1,idx.max(0)+1)
BC_IDs = np.ravel_multi_index(BC_arr.T,shp)
idx_IDs = np.ravel_multi_index(idx.T,shp)
return df[~np.in1d(BC_IDs,idx_IDs)]
def divakar(df, tuples):
idx = np.array(tuples)
mask = (df.B.values == idx[:, None, 0]) & (df.C.values == idx[:, None, 1])
return df[~mask.any(0)]
def pirsquared(df, tuples):
return df.set_index(list('BC')).drop(tuples).reset_index()
Run Code Online (Sandbox Code Playgroud)
10行,1元组
np.random.seed([3,1415])
df = pd.DataFrame(np.random.choice(range(10), (10, 3)), columns=list('ABC'))
tuples = [tuple(row) for row in np.random.choice(range(10), (1, 2))]
Run Code Online (Sandbox Code Playgroud)
10,000行,500元组
np.random.seed([3,1415])
df = pd.DataFrame(np.random.choice(range(10), (10000, 3)), columns=list('ABC'))
tuples = [tuple(row) for row in np.random.choice(range(10), (500, 2))]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2172 次 |
| 最近记录: |