我有以下 pandas 数据框:
id val city
4 78 a
4 12 b
4 50 c
9 20 d
9 8 e
9 30 f
9 17 g
我想把它转换成下面的形状。在每个“id”组中,根据“val”获取最大的行(本例中为 n=2)。例如78 和 50 位于 id 4 的组中,30 和 20 位于 id 9 的组中
id val city
4 78 a
4 50 c
9 30 f
9 20 d
最后,按如下方式旋转表格:
id c_1stLrgst c_1Lrgst_val c_2ndLrgst c_2Lrgst_val...c_nLrgst c_nLrgst_val
4 a 78 c 50
9 f 30 d 20
我可以使用df.groupby('id').nlargest(2, 'val')
获取组。不知道下一步该做什么。
import pandas as pd
df_dict = {'id': [4,4,4,9,9,9,9],
'val':[78,12,50,20,8,30,17],
'city':['a', 'b', 'c', 'd', 'e', 'f', 'g'],
};
df = pd.DataFrame(df_dict);
最佳答案
您可以使用 sort_values
+ groupby.head
,然后使用另一个 groupby
来列出
。然后拆分列表并连接。
# sort by "val" descending and extract first 2 rows from each group
df_filtered = df.sort_values('val', ascending=False)\
.groupby('id').head(2)
groupvars = ['city', 'val']
# groupby city and val
g = df_filtered.groupby('id')[groupvars].agg(list)
# split lists and create dataframe for each group key
L = [pd.DataFrame(g[x].values.tolist(), index=res.index).add_prefix(x) for x in groupvars]
# concatenate results
res = pd.concat(L, axis=1)
print(res)
city0 city1 val0 val1
id
4 a c 78 50
9 f d 30 20
关于python - 根据 pandas 中的列和数据透视中的一组查找最大值行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51179886/