我有一个数据框:
raw_data = {'cities': ['LA', 'LA', 'LA', 'Chicago', 'Chicago', 'Chicago', 'Chicago', 'Boston', 'Boston', 'Boston', 'Boston', 'Boston'],
'location': ['pub', 'dive', 'club', 'disco', 'cinema', 'cafe', 'diner', 'bowling','supermarket', 'pizza', 'icecream', 'music'],
'distance': ['0', '50', '100', '5', '75', '300', '20', '40', '70', '400', '2000', '2'],
'score': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['cities', 'location', 'distance', 'score'])
df
现在我正在尝试编写一个循环,以便对于每个城市,在迭代“距离”窗口内返回具有最高“分数”的“位置”。
即每 100 个单位得分最高的位置。
如何编写一个循环来执行此操作?
所需输出:
最佳答案
您可以创建一个假列,以每 100 个单位的范围内对距离进行分组。我首先将值为 0 的任何距离设置为值为 1,然后除以 100 并使用 numpy ceil 向上取整,这会得到一个整数范围,例如 0 到 100 公里之间的任何距离都会被分组在一起(值为假列中的 1)之后,我按城市和假列进行分组,获取每组中分数的最大索引,并将其定位回原始数据框中。最后,我们不希望最终输出中出现该假列,因此我使用 iloc (:-1) 将所有列切片直到最后一个:
df['t'] = pd.Series(pd.np.where(df['distance'].eq('0'), 1,
df['distance'])).astype(int).div(100).apply(pd.np.ceil)
df = df.iloc[df.groupby(['cities', 't'], sort=False)['score'].idxmax(), :-1]
print(df)
cities location distance score
1 LA dive 50 94
6 Chicago diner 20 94
5 Chicago cafe 300 25
11 Boston music 2 70
9 Boston pizza 400 70
10 Boston icecream 2000 62
关于python - 在考虑 Pandas DataFrame 中的多列的同时对组进行迭代操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57634352/