我有以下資料集。
col1 col2 col3
a 1 yes
a 1 no
b 1 no
a 3 yes
c 1 yes
b 2 yes
我使用交叉表在 col1 和 col2 之間創建了一個表并計算了觀察值。
pd.crosstab(df.col1, df.col2)
output:
col2 1 2 3
col1
a 2 0 1
b 1 1 0
c 1 0 0
如果我想要 groupby col3 的同一張表,我該怎么做?
Desired output:
col3: Yes col3: No
col2 1 2 3 col2 1 2 3
col1 col1
a 1 0 1 a 1 0 0
b 0 1 0 b 1 0 0
c 1 0 0 c 0 0 0
此外,有什么方法可以使表格更形象?
uj5u.com熱心網友回復:
您可以將列串列傳遞給pd.crosstab
:
x = pd.crosstab(df.col1, [df.col3, df.col2])
idx = pd.MultiIndex.from_product(
[
x.columns.get_level_values(0).unique(),
x.columns.get_level_values(1).unique(),
]
)
x = x.reindex(idx, axis=1, fill_value=0)
print(x)
印刷:
col3 no yes
col2 1 2 3 1 2 3
col1
a 1 0 0 1 0 1
b 1 0 0 0 1 0
c 0 0 0 1 0 0
uj5u.com熱心網友回復:
如果轉換col2
為Categorical
然后DataFrame.pivot_table
將所有類別添加到兩個級別:
df['col2'] = pd.Categorical(df['col2'])
df = df.pivot_table(index='col1',columns=['col3','col2'], aggfunc='size')
print (df)
col3 no yes
col2 1 2 3 1 2 3
col1
a 1 0 0 1 0 1
b 1 0 0 0 1 0
c 0 0 0 1 0 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/533413.html
上一篇:大熊貓resample()中STRING列的前填充或后填充
下一篇:根據過濾輸入選擇創建新列的函式