繁体   English   中英

如何将左表转换为汇总表?

[英]How can I convert a left table into a summary table?

如何将左表转换为右表?

截屏

我尝试使用 get dummies function 将值转换为 0 和 1。之后我不知道如何进行。

尝试这个:

import pandas as pd
import numpy as np
col1 = ['']+['Hampshire']*8+['']+['Hampshire']+['']+['Hampshire']+['','']+['Hampshire']*4
col2 = ['Southhampton'] + ['']*12 + ['Southhampton']*2 + ['']*4
col3 = ['']*11 + ['Isle of wight'] + ['']*7
col4 = ['Met']*5 + [''] + ['Met']*13
col5 = ['']*5 + ['Partially met'] + ['']*13
col6 = ['']*19

df = pd.DataFrame(data = dict(zip(['Hampshire', 'Southhampton', 'Isle of wight', '5met', '5partially met', '5Not met'],[col1,col2,col3,col4,col5,col6])))
df = df.replace('', np.nan)
df['Hampshire'] = df['Hampshire'].fillna(df['Southhampton'])
df['Hampshire'] = df['Hampshire'].fillna(df['Isle of wight'])
df[['Hampshire','5met','5partially met', '5Not met']].groupby(by=['Hampshire']).count()

我必须为您生成数据(因为除了图像之外您没有发布任何数据),但我认为这已经完成了。 我希望这有帮助。

使用stack重塑两个列块后使用crosstab

s1 = df[['Hampshire', 'Southhampton', 'Isle of wight']].stack().droplevel(-1)
s2 = df[['5met', '5partially met']].stack().droplevel(-1)

out = (pd.crosstab(s1, s2)
         .reindex(columns=['Met', 'Partially met', 'Not met'], fill_value=0)
         .rename_axis(columns=None, index=None)
       )

Output:

               Met  Partially met  Not met
Hampshire       13              1        0
Isle of wight    1              0        0
Southhampton     3              0        0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM