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

h6my8fg2  于 2023-06-04  发布在  其他
关注(0)|答案(2)|浏览(141)

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

我尝试使用get dummies函数将值转换为0和1。我不知道接下来该怎么办。

t98cgbkg

t98cgbkg1#

试试这个:

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()

我不得不为你生成数据(因为你没有发布任何除了图像),但我认为这是完成的工作。希望这能帮上忙。

798qvoo8

798qvoo82#

在使用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)
       )

输出:

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

相关问题