Python 如何从数据框中删除具有特定属性值的部分行

Python 如何从数据框中删除具有特定属性值的部分行,python,pandas,Python,Pandas,有了熊猫数据帧,如何有效地删除属性类中具有特定值(例如“低”)的部分行? 这是我的密码: import pandas as pd import numpy as np np.random.seed(3) df = pd.DataFrame({"a":[1,2,3,4], "b":[5,6,7,8], "class":['High','Low','Low','Low']}) drop_indices = np.random.choice(df.index, int(np.ceil(0.5*df.s

有了熊猫数据帧,如何有效地删除属性类中具有特定值(例如“低”)的部分行? 这是我的密码:

import pandas as pd
import numpy as np
np.random.seed(3)
df = pd.DataFrame({"a":[1,2,3,4], "b":[5,6,7,8], "class":['High','Low','Low','Low']})
drop_indices = np.random.choice(df.index, int(np.ceil(0.5*df.shape[0])) , replace=True)
df_subset = df.drop(drop_indices)
print df
print df_subset
输出:

   a  b class
0  1  5  High
1  2  6   Low
2  3  7   Low
3  4  8   Low
   a  b class
1  2  6   Low
3  4  8   Low

这是从所有类中删除,我希望它仅从class=Low中删除。

筛选到您要从中删除的行,使用选择要删除的部分成员,然后使用删除它们:

df = df.drop(df[df['class'] == 'Low'].sample(frac=0.33).index)
结果输出:

   a  b class
0  1  5  High
2  3  7   Low
3  4  8   Low

向下筛选到仅要从中删除的行,使用选择要删除的部分成员,然后使用删除它们:

df = df.drop(df[df['class'] == 'Low'].sample(frac=0.33).index)
结果输出:

   a  b class
0  1  5  High
2  3  7   Low
3  4  8   Low

另一种稍微不同的方法是使用布尔切片,保留所有非低位行,然后通过0-1随机数只保留低位行的一小部分

df[(df['class'] != 'Low') | (np.random.rand(len(df)) < .33)]
df[(df['class']!='Low')|(np.random.rand(len(df))<.33)]

另一种稍微不同的方法是使用布尔切片,保留所有非低位行,然后通过0-1随机数只保留低位行的一小部分

df[(df['class'] != 'Low') | (np.random.rand(len(df)) < .33)]
df[(df['class']!='Low')|(np.random.rand(len(df))<.33)]

您能帮我翻译一下吗。发布样本数据2。预期产出3。到目前为止你都试过了。请给我打电话,好吗。发布样本数据2。预期产出3。到目前为止你都试过了。密码?