gpt4 book ai didi

python - 带组但不带值字段的数据透视表

转载 作者:行者123 更新时间:2023-11-28 20:03:03 25 4
gpt4 key购买 nike

我有像这样的 pandas 数据框 url

location  dom_category
3 'edu'
3 'gov'
3 'edu'
4 'org'
4 'others'
4 'org'

我希望这个数据框是这样的

location  edu   gov   org   others
3 2 1 0 0
4 0 0 2 1

edu、gov、org 和其他包含特定位置的计数。我有正确的代码,但我知道它不是优化的

url['val']=1
url_final=url.pivot_table(index=['location'],values='val',columns=
['dom_category'],aggfunc=np.sum)

最佳答案

如有必要,首先通过 str.strip 删除 ' .

然后使用groupby聚合size并通过 unstack reshape :

df['dom_category'] = df['dom_category'].str.strip("\'")
df = df.groupby(['location','dom_category']).size().unstack(fill_value=0)
print (df)
dom_category edu gov org others
location
3 2 1 0 0
4 0 0 2 1

或者使用pivot_table :

df['dom_category'] = df['dom_category'].str.strip("\'")
df=df.pivot_table(index='location',columns='dom_category',aggfunc='size', fill_value=0)
print (df)
dom_category edu gov org others
location
3 2 1 0 0
4 0 0 2 1

最后可能将索引转换为列并删除列名 dom_category by reset_index + rename_axis :

df = df.reset_index().rename_axis(None, axis=1)
print (df)
location edu gov org others
0 3 2 1 0 0
1 4 0 0 2 1

关于python - 带组但不带值字段的数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44298779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com