删除多列条件下的行

2024-03-28 16:33:36 发布

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

我有一个熊猫数据框

pd_sequences
Out[3]: 
         0   1   2    3    4  5  occurence  unique      dist
0       58  68  58   59   -1 -1          5       3  0.030624
1       59  69  59   58   -1 -1         15       3  0.026485
2       93  94  93   33   -1 -1         10       3  0.137149
3       58  59  58   68   -1 -1          8       3  0.028127
4       92  94  92   33   -1 -1          4       3  0.155580
5       59  58  59   69   -1 -1         10       3  0.026057

其中前6个列名命名为0、1、2、3、4、5

如果0到5列中的任何一列包含数字100或101,我想删除该数据帧中的所有行。你知道吗

对于简单的单列:

#remove 100
pd_sequences.drop(pd_sequences[pd_sequences['0'] == 100].index, inplace=True)

然后呢

#remove 101
pd_sequences.drop(pd_sequences[pd_sequences['0'] == 101].index, inplace=True)

在不使布尔表达式太长的情况下,包含所有列的简单方法是什么?你知道吗


Tags: 数据trueindex表达式dist数字out命名
2条回答

尝试isinany的组合,并用~否定条件:

pd_sequences[~pd_sequences[['0', '1', '2', '3', '4', '5']].isin([100, 101]).any(1)]

您可以定义一个实现删除条件的函数,然后应用此函数选择行:

# This column represents rows satisfying the condition
bool_column = df.apply(lambda x: True if x[0] == 100 or x[1] == 101 else False, axis=1)
filtered_df = df[col.values]  # Select rows with True condition
filtered_df = df[~col.values]  # Select rows with False condition

在这里,这个函数被实现为lambda,但是在更复杂的计算中,它可以是一个普通的Python函数。如果条件中涉及的列太多,则也可以通过循环来实现自动化测向列. 此外,如果需要,可以在中向函数传递其他参数数据框应用. 你知道吗

相关问题 更多 >