我希望有一個包含專案索引、交易所串列和最后一列價格的最終資料框。
下面是一個例子:
data = {'Exchange': ['coinbase', 'binance', 'coinbase', 'ftx','coinbase'], 'Projects': ['Bitcoin', 'Bitcoin', 'Ethereum', 'Ethereum','Doge'],'Price': [10,5,10,2,10]}
df = pd.DataFrame(data)
Output :
Exchange Projects Price
0 coinbase Bitcoin 10
1 binance Bitcoin 5
2 coinbase Ethereum 10
3 ftx Ethereum 2
4 coinbase Doge 10
這是我嘗試過的
df2 = df.groupby(by=["Projects"]).count()
df2['Price'] = df['Price']
df2['Exchange'] = df['Exchange']
df2
Output:
Exchange Price
Projects
Bitcoin NaN NaN
Doge NaN NaN
Ethereum NaN NaN
我希望擁有的:
Exchange Price
Projects
Bitcoin coinbase,binance 10
Doge coinbase,ftx 2
Ethereum ftx 5
uj5u.com熱心網友回復:
使用groupby_agg:
>>> df.groupby('Projects').agg({'Exchange': ','.join, 'Price': 'last'})
Exchange Price
Projects
Bitcoin coinbase,binance 5
Doge coinbase 10
Ethereum coinbase,ftx 2
您可以替換'last'通過像另一個功能'max','mean','min'或自定義功能。
uj5u.com熱心網友回復:
在你的情況下
out = df.groupby('Projects').agg({'Exchange': ','.join,'Price':'last'})
Out[35]:
Exchange Price
Projects
Bitcoin coinbase,binance 5
Doge coinbase 10
Ethereum coinbase,ftx 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/346955.html
標籤:Python 蟒蛇-3.x 熊猫 数据框 pandas-groupby
