我有熊猫数据框网址
location dom_category
3 'edu'
3 'gov'
3 'edu'
4 'org'
4 'others'
4 'org'
Run Code Online (Sandbox Code Playgroud)
我希望这个数据框像
location edu gov org others
3 2 1 0 0
4 0 0 2 1
Run Code Online (Sandbox Code Playgroud)
edu、gov、org 和其他包含特定位置的计数。我有正确的代码,但我知道它不是优化的
url['val']=1
url_final=url.pivot_table(index=['location'],values='val',columns=
['dom_category'],aggfunc=np.sum)
Run Code Online (Sandbox Code Playgroud)
如有必要'
,首先删除str.strip
。
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
Run Code Online (Sandbox Code Playgroud)
或使用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
Run Code Online (Sandbox Code Playgroud)
最后可以将索引转换为列并dom_category
通过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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1292 次 |
最近记录: |