pandas drop 删除操作小记
2021-05-18 本文已影响0人
商鲲
1. 示例数据准备
import pandas as pd
data = {'counts': {'_八': 6, '塞外': 13, '_沙': 16,
'国_': 4, '与土': 17, '分国': 18,
'尘与': 18, '里路': 6, '_名': 12, '路云': 4}}
df = pd.DataFrame(data)
![](https://img.haomeiwen.com/i12105530/7bfc8b09eb7013b1.png)
2. 行删除
2.1 删除具体的行df1 = df.drop('塞外')
![](https://img.haomeiwen.com/i12105530/ffa5855184eb67f6.png)
2.2 根据行号删除行,例如删除第一行,df2 = df.drop(df.index[0])
![](https://img.haomeiwen.com/i12105530/25ad20b69036a3bc.png)
2.3 剔除不合要求的行,删除counts列值为6的行,df3 = df[df['counts'] != 6]
![](https://img.haomeiwen.com/i12105530/2494f4b302a9ceae.png)
2.4 剔除不符合要求的行,剔除index中包含'_'的行d4 = df[~ df.index.str.contains('_')]
![](https://img.haomeiwen.com/i12105530/c3ac917eeb55f3c3.png)
2.5 剔除不符合要求的行,只保留index中包含'_'的行,d5 = df[df.index.str.contains('_')]
![](https://img.haomeiwen.com/i12105530/6af2d73b0fc2e765.png)
3.列操作
3.1 根据列名删除具体的列df6 = df.drop('counts', axis=1)
打印df6,输出:
Columns: [] Index: [_八, _名, _沙, 与土, 分国, 国_, 塞外, 尘与, 路云, 里路]```