【问题标题】:How to solve issue with groupby on a dataframe如何解决数据框上的 groupby 问题
【发布时间】:2021-12-18 04:58:38
【问题描述】:

我希望有一个包含项目索引、交易所列表和最后一列价格的最终数据框。

这是一个例子:

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

【问题讨论】:

  • 价格如何获得 10、2、5?请检查您的输入和输出。为什么 'Doge' 在你的输出中有 'coinbase,ftx'?

标签: python python-3.x pandas dataframe pandas-groupby


【解决方案1】:

使用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' 或自定义函数。

【讨论】:

  • 感谢您的帮助!但在这里我们没有得到不同的价格......但仍然有很大的帮助。我会找到办法的
【解决方案2】:

你的情况

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

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 2020-08-19
    • 1970-01-01
    • 2021-08-14
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    相关资源
    最近更新 更多