pandas-删除-某个值大于多少的-整行
假设我们有一个名为df的DataFrame,其中包含数值数据,我们想要删除其中值大于某个数的整行,可以按照以下步骤进行操作:
- 使用
df.loc方法选择要删除的行,条件是其中一列的值大于某个数,例如:
df.loc[df['column_name'] > threshold]
其中,column_name是要比较的列名,threshold是要删除的阈值。
- 调用
df.drop方法删除这些行,例如:
df.drop(df.loc[df['column_name'] > threshold].index, inplace=True)
其中,df.loc[df['column_name'] > threshold].index是要删除的行的索引列表,inplace=True表示在原始DataFrame上进行修改。
完整示例代码如下:
import pandas as pd
# 创建示例数据
data = {'name': ['Alice', 'Bob', 'Charlie', 'David'],
'age': [25, 30, 35, 40],
'score': [80, 90, 85, 95]}
df = pd.DataFrame(data)
# 删除分数大于等于90的学生
threshold = 90
df.drop(df.loc[df['score'] >= threshold].index, inplace=True)
print(df)
输出结果为:
name age score
0 Alice 25 80
2 Charlie 35 85
可以看到,Bob和David这两个学生的行被成功删除了。
原文地址: http://www.cveoy.top/t/topic/mFI 著作权归作者所有。请勿转载和采集!