【问题标题】:Compare several values of pandas dataframe with the same id比较具有相同 id 的 pandas 数据帧的几个值
【发布时间】:2020-11-07 11:41:25
【问题描述】:

我有一个具有这种结构的 df:

         paramter    names   ids
0        0.008        t        1
1        0.349        P1       1
2        0.120        P2       1
3        0.008        t        2
4        0.349        P1       2
5        0.120        P2       2 
6        0.209        t        3
7        0.349        P1       3
8        0.200        P2       3
9        0.209        t        4
10       0.349        P1       4
11       0.200        P2       4
...      ...             ...     ...
3000

我想为每个元素提取给定的id,P1,P2,t的参数。如果一个元素的所有参数都与另一个元素的参数相同,那么我想将它们添加到同一个列表中。这里 1,2 将在同一个列表中,而 3,4 在另一个列表中,因为 1 的所有三个值都对应于 2,而 3 的所有三个值都对应于 4。

我不知道我有多少不同的元素,所以我不知道我需要多少个列表。

【问题讨论】:

    标签: python pandas list dataframe


    【解决方案1】:

    使用pivot 重塑数据框,索引为id,列为names,值为parameter,然后在P1, p2, t 上使用groupby,并在列表理解中收集属于同一组的ID:

    df1 = df.pivot('ids', 'names', 'paramter').reset_index()
    ids = [g['ids'].tolist() for _, g in df1.groupby(['P1', 'P2', 't'])]
    

    详情:

    print(df1)
    names  ids     P1    P2      t
    0        1  0.349  0.12  0.008
    1        2  0.349  0.12  0.008
    2        3  0.349  0.20  0.209
    3        4  0.349  0.20  0.209
    
    print(ids)
    [[1, 2], [3, 4]]
    

    【讨论】:

    • 谢谢!你的回答非常适合我的情况:)
    • @Heimson 编码快乐!
    猜你喜欢
    • 2014-06-02
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 2016-02-28
    • 2022-07-20
    • 2020-11-05
    相关资源
    最近更新 更多