python - 熊猫爆炸避免重复值
问题描述
我在多列中有以下数据:
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
解决方案
我想要列表中元素的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
推荐阅读
- django - Django 模型自动修改日期问题
- c# - API 托管在 Azure 中,但数据库托管在我们的网络中
- regression - 存储每组的残差
- json - 在 Flutter 中将 JSON 解析为模型
- python-3.x - 如何使用 pip 将软件包安装到自定义目录但尊重依赖关系
- java - 在 getter 和 setter 中使用扫描仪输入?
- sql - 我们如何仅在 Oracle 11G SQL 中显示表中的最后 7 条记录?
- python - 如何使用 Python 获取 Python 模块中的类依赖项列表?
- google-apps-script - 服务不可用:复制 Google Docs 时的 DOCS
- php - 您的要求无法通过 laragon 服务器解决为一组可安装的软件包