识别两列之间的关系及其在熊猫中的各自价值计数

时间:2020-01-08 05:34:40

标签: python-3.x pandas

我的数据框如下:

Col1    Col2    Col3    Col4
1       111     a       Test
2       111     b       Test
3       111     c       Test
4       222     d       Prod
5       333     e       Prod
6       333     f       Prod
7       444     g       Test
8       555     h       Prod
9       555     i       Prod

预期输出:

Column 1    Column 2    Relationship    Count
Col2        Col3        One-to-One       2
Col2        Col3        One-to-Many      3

说明: 我需要确定Col2和Col3之间的关系以及值计数。

例如111(col2)重复3次,在Col3中具有3个不同的相应值a,b,c。 这意味着col2和col3具有一对多关系-count_1:1

222(col2)不重复并且在col3中只有一个相应的值d。 这意味着col2和col3具有一对一的关系-count_2:1

333(col2)重复两次,并在col3中具有2个不同的相应值e,f。 这意味着col2和col3具有一对多关系-count_1:1 + 1(对于每个一对多关系,递增此计数)

对于其他列值,类似地,递增各自的计数器并将最终结果显示为预期的数据帧。

1 个答案:

答案 0 :(得分:1)

如果只需要检查col2和col3之间的关系,则可以执行以下操作:

(
    df.groupby(by='Col2').Col3
    .apply(lambda x: 'One-to-One' if len(x)==1 else 'One-to-Many')
    .to_frame('Relationship')
    .groupby('Relationship').Relationship
    .count().to_frame('Count').reset_index()
    .assign(**{'Column 1':'Col2', 'Column 2':'Col3'})
    .reindex(columns=['Column 1', 'Column 2', 'Relationship', 'Count'])
)

输出:

    Column 1    Column 2    Relationship    Count
0   Col2        Col3        One-to-Many     3
1   Col2        Col3        One-to-One      2