Pandas 数据帧drop()
方法
原文:https://www.studytonight.com/pandas/pandas-dataframe-drop-method
在本教程中,我们将学习 PandasDataFrame.drop()
T3】法。它从行或列中删除指定的标签。它通过指定标签名和相应的轴,或者通过直接指定索引或列名来删除行或列。使用多索引时,可以通过指定级别来移除不同级别上的标签。
它返回数据帧或无。没有删除索引或列标签的数据帧,或者
inplace=True.
为无如果在所选轴中找不到任何标签,将引发
KeyError
异常。
下图显示了DataFrame.drop()
方法的语法。
句法
DataFrame.drop(labels=None,axis=0,index=None,columns=None,level=None,inplace=False,errors='raise')
因素
标签:单个标签或列表状。要删除的索引或列标签。
轴: {0 或'索引',1 或'列' },默认为 0。是从索引(0 或“索引”)还是从列(1 或“列”)中删除标签。
索引:单个标签或列表状。指定轴的替代方法(标签,轴=0 相当于索引=标签)。
列:单个标签或列表状。指定轴的替代方法(标签,轴=1 相当于列=标签)。
级别: int 或级别名称,可选。对于多索引,标签将被移除的级别。
inplace: bool,默认 False。如果为假,则返回副本。否则,就地操作并返回无。
错误: { '忽略','提高' },默认为'提高'。如果“忽略”,抑制错误,仅删除现有标签。
示例 1:使用 DataFrame.drop()方法删除行
DataFrame.drop()
方法沿着row
轴从数据帧中删除指定的标签。下面的例子显示了同样的情况。
import pandas as pd
df=pd.DataFrame([[0,1,2,3], [4,5,6,7],[8,9,10,11]],columns=('a','b','c','d'))
print("------DataFrame-------")
print(df)
print("------After dropping a specific label from the row of the DataFrame-------")
print(df.drop(1))
一旦我们运行该程序,我们将获得以下输出。
-数据帧- a b c d 0 1 2 3 1 4 5 6 7 2 8 9 10 11 -从数据帧的行中删除特定标签后- a b c d 0 1 2 3 2 8 9 10 11
示例 2:使用 DataFrame.drop()方法删除行
DataFrame.drop()
方法通过交替指定轴index=1
从数据帧中删除指定的标签。下面的例子显示了同样的情况。
import pandas as pd
df=pd.DataFrame([[0,1,2,3], [4,5,6,7],[8,9,10,11]],columns=('a','b','c','d'))
print("------DataFrame-------")
print(df)
print("------------After dropping a specific label from the row of the DataFrame---------")
print(df.drop(index=1))
一旦我们运行该程序,我们将获得以下输出。
-数据帧- a b c d 0 1 2 3 1 4 5 6 7 2 8 9 10 11 -从数据帧的行中删除特定标签后- a b c d 0 1 2 3 2 8 9 10 11
示例 3:使用 DataFrame.drop()方法删除行
DataFrame.drop()
方法沿着column
轴从数据帧中删除指定的标签。下面的例子显示了同样的情况。
import pandas as pd
df=pd.DataFrame([[0,1,2,3], [4,5,6,7],[8,9,10,11]],columns=('a','b','c','d'))
print("------DataFrame-------")
print(df)
print("------After dropping a specific label from the column of the DataFrame-------")
print(df.drop('b',axis=1))
一旦我们运行该程序,我们将获得以下输出。
-数据帧- a b c d 0 1 2 3 1 4 5 6 7 2 8 9 10 11 -从数据帧的列中删除特定标签后- a c d 0 2 3 1 4 6 7 2 8 10 11
示例 4:使用 DataFrame.drop()方法删除行
DataFrame.drop()
方法通过交替指定轴column=’b’
从数据帧中删除指定的标签。下面的例子显示了同样的情况。
import pandas as pd
df=pd.DataFrame([[0,1,2,3], [4,5,6,7],[8,9,10,11]],columns=('a','b','c','d'))
print("------DataFrame-------")
print(df)
print("------After dropping a specific label from the column of the DataFrame-------")
print(df.drop(columns='b'))
一旦我们运行该程序,我们将获得以下输出。
-数据帧- a b c d 0 1 2 3 1 4 5 6 7 2 8 9 10 11 -从数据帧的列中删除特定标签后- a c d 0 2 3 1 4 6 7 2 8 10 11
示例 5:使用 DataFrame.drop()方法删除行
如果在所选轴中没有找到任何标签,DataFrame.drop()
方法将引发KeyError
。
import pandas as pd
df=pd.DataFrame([[0,1,2,3], [4,5,6,7],[8,9,10,11]],columns=('a','b','c','d'))
print("------After dropping a specific label from the row of the DataFrame-------")
print(df.drop(5))
一旦我们运行该程序,我们将获得以下输出。
-从数据帧的行中删除特定标签后- 键错误:“[5]在轴中找不到”
结论
在本教程中,我们学习了 PythonPandasDataFrame.drop()
方法。我们学习了语法、参数,并通过向方法传递不同的参数来解决示例。