美文网首页
Python Pandas 依据属性值删除dataframe的行

Python Pandas 依据属性值删除dataframe的行

作者: 王叽叽的小心情 | 来源:发表于2020-08-22 00:09 被阅读0次

之前写过,依据索引/下标删除DataFrame的行或者列,参见pandas dataframe 删除行 drop row。不过发现,更多的时候,是知道某一列属性值,依据属性值进行删除。

举个例子,现在有中国340个地级市,想要删除三沙市、香港和澳门,该属性值所在的列为city,那么如何做呢,主要用到了isin()函数以及如何取反,完整代码如下:

# 拟删除城市-人口文件中三沙市、香港和澳门所在的行

# 读取文件并重新命名列
input_path = "D:\\wyx2020\\"
file = "city_people.csv"
df = pd.read_csv(input_path+file, header=0, encoding='utf-8',
                     names=['city','people'])

# 指定需要删除的城市列表
del_city_list = ['海南省_三沙市','香港特别行政区_香港特别行政区',
                     '澳门特别行政区_澳门特别行政区']

# 采用isin()函数筛选取反,重新定义一个dataframe进行获取
df_out = df[~df_city.isin(del_city_list)]

# 输出文件
df_out.to_csv(input_path+'city_people_del.csv', header=True, index=False, encoding='gbk')

参考资料:
How to filter Pandas dataframe using 'in' and 'not in' like in SQL

相关文章

网友评论

      本文标题:Python Pandas 依据属性值删除dataframe的行

      本文链接:https://www.haomeiwen.com/subject/hyjmjktx.html