【问题标题】:Add a column that contains a list of ID's from another dataframe添加一列,其中包含来自另一个数据框的 ID 列表
【发布时间】:2018-11-09 03:45:18
【问题描述】:

问题
我想在数据帧上执行groupby,生成的数据帧包含一个列,其元素是groupby 参数的列表。

示例
我有一个数据框ship_clusterShipIDlatitudelongitude 和一个名为cluster 的列。

In [4]: df = pd.DataFrame({"ShipID": [7, 7, 8, 9],
                           "latitude": [51.872842, 51.872874, 51.872794, 51.872946],
                           "longitude": [5.810379, 5.810729, 5.810754, 5.810548],
                           "cluster": [0, 1, 0, 0]})
print(df)

"ShipID" latitude  longitude cluster
7        51.872842 5.810379  0
7        51.872874 5.810729  1
8        51.872794 5.810754  0
9        51.872946 5.810548  0

我希望得到的输出是:

         latitude  longitude ShipID
cluster                            
0        51.872860 5.810560  [7, 8, 9]
1        51.872874 5.810729  [7]

所以根据cluster,我想在列表中看到ShipID。显然,我可以先做一个groupby:

ship_cluster[["latitude", "longitude", cluster"]].groupby("cluster").mean()

但是我不知道下一步,也没有简化的方法。有什么帮助吗?

【问题讨论】:

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


    【解决方案1】:

    如果需要,我相信需要由cluster 汇总:

    d = {"latitude":'mean', "longitude":'mean', "ShipID":lambda x: x.tolist()}
    df = ship_cluster.groupby("cluster").agg(d)
    print (df)
             latitude  longitude ShipID
    cluster                            
    0        51.87270    5.81362    [7]
    1        51.85040    5.86688    [7]
    2        51.87410    5.91493    [7]
    3        51.85500    5.96898    [7]
    4        51.88101    6.00426    [7]
    5        51.87368    6.03096    [7]
    

    ShipID:

    d = {"latitude":'mean', "longitude":'mean', "cluster":lambda x: x.tolist()}
    df = ship_cluster.groupby("ShipID").agg(d)
    print (df)
             latitude  longitude             cluster
    ShipID                                          
    7       51.867815   5.933272  [0, 1, 2, 3, 4, 5]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 2022-01-24
      • 2021-08-31
      相关资源
      最近更新 更多