如何在 Python pandas 中重塑此数据集?

How do I reshape this dataset in Python pandas?

假设我有这样一个数据集:

is_a  is_b  is_c  population infected
1     0     1     50         20
1     1     0     100        10
0     1     1     20         10
...

如何将其重塑为这样的形状?

feature  0       1 
a        10/20   30/150
b        20/50   20/120
c        10/100  30/70
...

在原始数据集中,我将特征 abc 作为它们自己单独的列。在转换后的数据集中,这些相同的变量列在列 feature 下,并生成两个新列 01,对应于这些特征可以采用的值。

is_a0 的原始数据集中,添加 infected 个值并将它们除以 population 个值。其中 is_a1,做同样的事情,添加 infected 个值并将它们除以 population 个值。冲洗并重复 is_bis_c。如图所示,新数据集将具有这些分数(或小数)。谢谢!

我已经尝试了 pd.pivot_tablepd.melt,但没有什么能满足我的需要。

做了wide_to_long之后,你的问题就更清楚了

df=pd.wide_to_long(df,['is'],['population','infected'],j='feature',sep='_',suffix='\w+').reset_index()
df
  population  infected feature is
0          50        20    a   1
1          50        20    b   0
2          50        20    c   1
3         100        10    a   1
4         100        10    b   1
5         100        10    c   0
6          20        10    a   0
7          20        10    b   1
8          20        10    c   1

df.groupby(['feature','is']).apply(lambda x : sum(x['infected'])/sum(x['population'])).unstack()
is      0         1
feature
a     0.5  0.200000
b     0.4  0.166667
c     0.1  0.428571

我在你的小数据框上试过这个,但我不确定它是否适用于更大的数据集。

dic_df = {}
for letter in ['a', 'b', 'c']: 
    dic_da = {}
    dic_da[0] = df[df['is_'+str(letter)] == 0].infected.sum()/df[df['is_'+str(letter)] == 0].population.sum()
    dic_da[1] = df[df['is_'+str(letter)] == 1].infected.sum()/df[df['is_'+str(letter)] == 1].population.sum()
    dic_df[letter] = dic_da
    dic_df
dic_df_ = pd.DataFrame(data = dic_df).T.reset_index().rename(columns= {'index':'feature'})

feature 0   1
0   a   0.5 0.200000
1   b   0.4 0.166667
2   c   0.1 0.428571

在这里,DF 将是您的原始 DataFrame

Aux_NewDF = [{'feature': feature, 
               0       : '{}/{}'.format(DF['infected'][DF['is_{}'.format(feature.lower())]==0].sum(), DF['population'][DF['is_{}'.format(feature.lower())]==0].sum()), 
               1       : '{}/{}'.format(DF['infected'][DF['is_{}'.format(feature.lower())]==1].sum(), DF['population'][DF['is_{}'.format(feature.lower())]==1].sum())} for feature in ['a','b','c']] 



NewDF = pd.DataFrame(Aux_NewDF)