![](/img/trans.png)
[英]pandas: how to select first or last by column in keep with drop_duplicates
[英]Averaging duplicates in a pandas DataFrame instead of using drop_duplicates to keep first
假設我有一個Pandas DataFrame
的形式:
id price dur
1 153 80.0 0.0
2 153 130.0 0.0
3 153 95.0 0.0
4 156 115.0 0.0
5 156 165.0 0.0
6 156 130.0 0.0
7 158 90.0 0.0
8 158 140.0 0.0
9 158 105.0 0.0
10 158 155.0 0.0
我有一個名為id
的列,它有duplicates
。 我想通過保留unique
id
然后執行id
的平均price
而不是使用pd.DataFrame.drop_duplicates()
來處理這種duplicates
這是我預期的 output:
id price dur
1 153 101.667 0.0
2 156 136.667 0.0
3 158 122.5 0.0
我怎么可能處理這個?
對於每一列,必須在 GroupBy.agg 中指定聚合GroupBy.agg
:
df1 = df.groupby('id', as_index=False).agg({'price':'mean', 'dur':'first'})
print (df1)
id price dur
0 153 101.666667 0.0
1 156 136.666667 0.0
2 158 122.500000 0.0
但是,如果每個id
的dur
中的相同值可以按兩列分組:
df2 = df.groupby(['id', 'dur'], as_index=False)['price'].mean()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.