说我有一个像这样的数据集:
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
...
在原始数据集,我有特点a
,b
和c
作为自己单独的列。在转换后的数据集中,这些相同的变量列在column之下feature
,并产生两个新列0
,1
分别对应于这些要素可以采用的值。
在原始数据集,其中is_a
是0
,增加infected
值,并通过它们划分population
值。在is_a
is处1
,执行相同操作,添加infected
值并将它们除以population
值。冲洗并为is_b
和重复is_c
。如图所示,新的数据集将具有这些分数(或小数)。谢谢!
我已经尝试过pd.pivot_table
,pd.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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句