Python - 从多索引 Pandas 数据框中删除特定行
要从多索引数据帧中删除特定行,请使用该drop()方法。首先,让我们创建一个多索引数组 -
arr = [np.array(['car', 'car', 'car','bike', 'bike', 'bike', 'truck', 'truck', 'truck']),np.array(['valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC'])]
接下来,创建多索引数据帧并设置索引 -
dataFrame = pd.DataFrame(np.random.randn(9, 3), index=arr, columns=['Col 1', 'Col 2', 'Col 3'])
dataFrame.index.names = ['level 0', 'level 1']
现在,删除特定行 -
dataFrame.drop(('car','valueA'), axis=0, inplace=True)
示例
以下是代码 -
import numpy as np输出结果import pandas as pd
# multiindex array
arr = [np.array(['car', 'car', 'car','bike','bike', 'bike', 'truck', 'truck', 'truck']),
np.array(['valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC'])]
# forming multiindex dataframe
dataFrame = pd.DataFrame(
np.random.randn(9, 3), index=arr,columns=['Col 1', 'Col 2', 'Col 3'])
dataFrame.index.names = ['level 0', 'level 1']
print(dataFrame)
print("\nDropping specific row...\n");
dataFrame.drop(('car','valueA'), axis=0, inplace=True)
print(dataFrame)
这将产生以下输出 -
Col 1 Col 2 Col 3level 0 level 1
car valueA 0.845965 -0.850953 -0.335662
valueB 0.534764 -0.107635 1.008855
valueC -0.507910 -0.664625 1.671653
bike valueA -0.475751 -0.244113 0.672352
valueB -0.273670 1.118635 0.428750
valueC -1.064504 -0.344729 0.481037
truck valueA -0.508659 1.352390 1.382799
valueB 1.144299 -0.092568 -1.071624
valueC -0.710767 0.967018 -0.047430
Dropping specific row...
Col 1 Col 2 Col 3
level 0 level 1
car valueB 0.534764 -0.107635 1.008855
valueC -0.507910 -0.664625 1.671653
bike valueA -0.475751 -0.244113 0.672352
valueB -0.273670 1.118635 0.428750
valueC -1.064504 -0.344729 0.481037
truck valueA -0.508659 1.352390 1.382799
valueB 1.144299 -0.092568 -1.071624
valueC -0.710767 0.967018 -0.047430
以上是 Python - 从多索引 Pandas 数据框中删除特定行 的全部内容, 来源链接: utcz.com/z/359086.html