首页 > 解决方案 > 熊猫爆炸避免重复值

问题描述

我在多列中有以下数据:

    col1             col2                       col3
123456     ['mary','ralph', ''bob']     ['bob','sam']
456789     ['george','fred', susie']  ['ralph','mary', 'bob']
789123     ['mary', bob']             ['bob']

我最终需要在每一列上都有一个 value_counts 。为了使所有内容都脱离列表,我正在尝试爆炸。我可以在爆炸后将值放入它们的列中,没问题。但是,那些了解爆炸的人都知道,我的 value_counts 会被夸大,因为在将它应用于多个列时会导致爆炸导致的值重复

例如,爆炸会产生:

  col1     col2     col3
123456     mary     bob
123456     mary     sam     
123456     mary     george
123456     ralph    bob
123456     ralph    sam     
123456     ralph    george...etc.

显然,这会抛出我需要的每列的准确 value_counts。我尝试在每列上循环爆炸,然后在每列爆炸匹配第一个列和爆炸列并删除重复项后,不起作用。总是喜欢不做房间里最聪明的人(更多要学习)所以我把这个问题发给了你的熊猫大师,想法爆炸了。(看看我在那里做了什么?)。谢谢。

预期的输出,以便我可以对除 col1 之外的所有列进行 value_counts 是这样的:

123456    mary     bob
123456   ralph     sam
123456     bob  george
456789  george   ralph
456789    fred    mary
456789   susie     bob
789123    mary     bob
789123     bob  george

标签: pythonpandasexplode

解决方案


我想要列表中元素的value_counts,首先你需要平列然后取value_counts,例如:

import pandas as pd
from itertools import chain

df = pd.DataFrame(data=[
    [123456, ['mary', 'ralph', 'bob'], ['bob', 'sam', 'george']],
    [456789, ['george', 'fred', 'susie'], ['ralph', 'mary', 'bob']],
    [789123, ['mary', 'bob'], ['bob', 'george']]
], columns=['col1', 'col2', 'col3'])

print(pd.Series(chain.from_iterable(df['col2'])).value_counts())

输出

mary      2
bob       2
susie     1
george    1
fred      1
ralph     1
dtype: int64

上面的结果是您的示例的value_counts 。col2


推荐阅读