看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)以下的 DataFrame 有两列,其中 tags 列每行是一个列表,列表的每个元素是一个 tag 标签,求标签及其数量。
import pandas as pd
data = {
'id': ['item1', 'item2', 'item3', 'item4'],
'tags': [['friends','family'], ['friends'], [], ['family','holiday']]
}
df = pd.DataFrame(data)
df
'''
id tags
0 item1 [friends, family]
1 item2 [friends]
2 item3 []
3 item4 [family, holiday]
'''
期望结果为:
'''
family 2
friends 2
holiday 1
'''
以下为 Python 代码:
(
df.explode('tags')
.groupby('tags')
.size()
)
'''
tags
family 2
friends 2
holiday 1
dtype: int64
'''
查看相关链接中的知识。
(完)
更新时间:2025-02-04 08:48:05 标签:pandas python 标签