Skip to main content
 首页 » 编程设计

python之删除数据框中的行数

2024年12月31日8tintown

我有一个数据框包含 25000 行和两列(文本,类) 类包含一些[A,B,C]

data = pd.read_csv('E:\mydata.txt', sep="*") 
data.columns = ["text", "class"] 

我需要删除例如 A 类的 10 行,B 类的 15 行

请您参考如下方法:

您可以通过条件切片和数据帧的索引属性来实现这一点

remove_n = 10 
remove_class = 1 
# Here you first find the indexes where class is equal to the class you want to drop. 
#Then you slice only the first n indexes of this class 
index_to_drop = data.index[data['class'] == remove_class][:remove_n] 
#Finally drop those indexes 
data = data.drop(index_to_drop)