Group operations on Pandas column containing lists

后端 未结 2 538
南笙
南笙 2021-01-18 13:00

I have a DataFrame containing a column, props, which contains lists of strings.

Ideally, I\'d like to group by this column, but I predictably get an err

2条回答
  •  萌比男神i
    2021-01-18 13:48

    You can use the immutable counterpart to lists, which are tuples:

    >>> import pandas as pd
    >>> df = pd.DataFrame([[[1, 2], 'ab'], [[2, 3], 'bc']])
    >>> df.groupby(0).groups
    ...
    ... TypeError: unhashable type: 'list'
    

    You could apply the conversion on the appropriate column:

    >>> df[0] = df[0].apply(tuple)
    >>> df.groupby(0).groups
    {(1, 2): [0], (2, 3): [1]}
    

提交回复
热议问题