假设我有以下数据帧:
Row | Temperature | Measurement
A1 | 26.7 | 12
A1 | 25.7 | 13
A2 | 27.3 | 11
A2 | 28.3 | 12
A3 | 25.6 | 17
A3 | 23.4 | 14
----------------------------
P3 | 25.7 |14
我想删除与 'Row' 列相关的重复行,并且我只想保留 Temperature 列中值最接近 25 的行。 例如:
Row | Temperature | Measurement
A1 | 25.7 | 13
A2 | 27.3 | 11
A3 | 25.6 | 17
----------------------------
P3 | 25.7 |14
我正在尝试使用此函数在数组中查找最近的:
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
array = df['Temperature']
value = 25
但我不确定如何在 df 中处理 pandas.drop_duplicates
。谢谢!
python
pandas
dataframe
答案 0 :(得分:0)
一种方法是创建一个临时列并对其进行排序,然后删除重复项:
df['key'] = df['Temperature'].sub(25).abs()
# sort by key, drop duplicates, and resort
df.sort_values('key').drop_duplicates('Row').sort_index()
输出:
Row Temperature Measurement key
1 A1 25.7 13 0.7
2 A2 27.3 11 2.3
4 A3 25.6 17 0.6
6 P3 25.7 14 0.7
另一个选项,类似于您正在尝试做的,是在键上使用 np.argsort
,并按 iloc
排序。这避免了在数据中创建新列:
orders = np.argsort(df['Temperature'].sub(25).abs())
df.iloc[orders].drop_duplicates('Row').sort_index()
输出:
Row Temperature Measurement
1 A1 25.7 13
2 A2 27.3 11
4 A3 25.6 17
6 P3 25.7 14