Pandas 枢轴 table 计数
Pandas pivot table count
我想问一个关于 Pandas 中枢 tables 的问题。
我一直在尝试为这种 table:
做一个支点 table
sector
score
US
null
US
null
US
1
EU
null
EU
2
EU
2
EU
4
UK
null
UK
null
UK
null
UK
4
UK
4
最终,我希望这个 table 成为一个支点 table,看起来像这样:
null
1
2
4
US
2
1
0
0
EU
1
0
2
1
UK
3
0
0
2
为了做到这一点,我一直在努力做到以下几点:
import pandas as pd
import numpy as np
df = sql("SELECT sector, score FROM database")
df_piv = pd.pivot_table(
df,
index = 'sector',
columns = 'score',
values = 'score',
aggfunc = 'count'
)
但是,这样做时,我不断收到以下错误:
ValueError: Cannot convert column into bool: please use '&' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions.
你能帮帮我吗?
谢谢:)
我比较喜欢用groupby
,你可以用
>>> df.groupby('sector')['score'].value_counts(dropna=False).unstack(fill_value=0)
score NaN 1.0 2.0 4.0
sector
EU 1 0 2 1
UK 3 0 0 2
US 2 1 0 0
旁注:
如果不想计算缺失值,
pd.pivot_table(df, index='sector', columns='score', aggfunc=len, fill_value=0)
就可以了。使用 len
作为实际函数,因为出于某种原因 pivot_table
的 aggfunc
参数似乎不接受像 groupby.agg
/transform
.[=18 这样的字符串快捷方式=]
我想问一个关于 Pandas 中枢 tables 的问题。
我一直在尝试为这种 table:
sector | score |
---|---|
US | null |
US | null |
US | 1 |
EU | null |
EU | 2 |
EU | 2 |
EU | 4 |
UK | null |
UK | null |
UK | null |
UK | 4 |
UK | 4 |
最终,我希望这个 table 成为一个支点 table,看起来像这样:
null | 1 | 2 | 4 | |
---|---|---|---|---|
US | 2 | 1 | 0 | 0 |
EU | 1 | 0 | 2 | 1 |
UK | 3 | 0 | 0 | 2 |
为了做到这一点,我一直在努力做到以下几点:
import pandas as pd
import numpy as np
df = sql("SELECT sector, score FROM database")
df_piv = pd.pivot_table(
df,
index = 'sector',
columns = 'score',
values = 'score',
aggfunc = 'count'
)
但是,这样做时,我不断收到以下错误:
ValueError: Cannot convert column into bool: please use '&' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions.
你能帮帮我吗?
谢谢:)
我比较喜欢用groupby
,你可以用
>>> df.groupby('sector')['score'].value_counts(dropna=False).unstack(fill_value=0)
score NaN 1.0 2.0 4.0
sector
EU 1 0 2 1
UK 3 0 0 2
US 2 1 0 0
旁注:
如果不想计算缺失值,
pd.pivot_table(df, index='sector', columns='score', aggfunc=len, fill_value=0)
就可以了。使用 len
作为实际函数,因为出于某种原因 pivot_table
的 aggfunc
参数似乎不接受像 groupby.agg
/transform
.[=18 这样的字符串快捷方式=]