这些是数组中的数据帧(此数组的名称为clusters(:
[ Height Weight
STU3 72.508120 216.218230
STU2 70.183550 201.071918
STU4 71.252986 204.655494,
Height Weight
STU18 64.756280 137.348471
STU11 63.075024 146.905558
STU16 63.981765 147.812869,
Height Weight
STU12 56.810317 84.170695,
Height Weight
STU1 65.270346 168.617746
STU6 65.806248 165.850648
STU7 68.096220 167.747141
STU9 66.166363 165.514607
STU10 67.906850 170.417231,
Height Weight
STU5 65.237050 181.011973
STU8 67.155963 175.646690
STU20 69.443615 178.276728,
Height Weight
STU18 64.756280 137.348471
STU11 63.075024 146.905558
STU16 63.981765 147.812869,
Height Weight
STU17 61.253579 109.681758
STU13 60.916196 120.943248
STU19 60.236390 123.863208
STU14 63.383506 125.662081
STU15 60.822118 127.441434]
这是我想从上面的数组中删除的数据帧(称为biggest_cluster(:
[ Height Weight
STU18 64.756280 137.348471
STU11 63.075024 146.905558
STU16 63.981765 147.812869]
因此,我删除此数据帧的代码片段如下:
clusters.remove(biggest_cluster)
我得到的错误是:ValueError: Can only compare identically-labeled DataFrame objects
通常,在比较数据帧时会出现此错误。然而,在这种情况下,我只是试图从数组中删除一个元素(在这种情况中,它恰好是一个数据帧((在这种情形中,数组存储数据帧(。
如何解决此问题?
list.remove
方法确实会比较DataFrames是否相等(==
(。来自Python文档(重点添加(:
list.remove(x)
从列表中删除值等于x的第一个项目如果不存在此类项,则引发ValueError。
在比较列表中的第一个DataFrame时,由于行标签与biggest_cluster
不同,此操作已失败。
有很多方法可以解决这个问题,所有这些方法都比.remove
长一点。比较简单和可读的是测试身份而不是平等的列表理解:
clusters = [cluster for cluster in clusters if cluster.equals(biggest_cluster)]
一个缺点是:在垃圾收集器处理之前,该列表将在内存中存在两次。如果数据量很大,这可能是个问题。
在Pandas DataFrame的上下文中,与==
进行比较意味着元素比较,如果标签不匹配,这种比较就不起作用,而我在上面使用的pd.DataFrame.equals
则检查整个DataFrame是否相同。
以下是使用的可能解决方案
df1.drop(df2.index.values,inplace=True)
import pandas as pd
import numpy as np
# Matrix of a few sample values.
my_matrix = np.matrix([
[72.508120,216.218230],
[70.183550, 201.071918],
[71.252986, 137.348471],
[64.756280, 204.655494],
[63.075024, 146.905558]
]
)
index = ['STU1','STU2','STU3','STU4','STU4']
# Instanced as my_df
my_df = pd.DataFrame(data= my_matrix, index= index, columns=['Height','Name'])
# Sample of what big cluster could be
my_other_matrix = np.matrix([
[64.756280, 204.655494],
[63.075024, 146.905558]
]
)
# Now as a df
my_other_df = pd.DataFrame(data= my_other_matrix, index= ['STU1','STU2'], columns=['Height', 'Name'])
# Assume we wish to remove indices STU1 and STU2.
# Drop the values that correspond to the indices of big-cluster
my_df.drop(my_other_df.index.values,inplace=True)
print(my_df)
请注意,就地处理任务。