Python 数据帧:计算行之间的百分比差异?

Python 数据帧:计算行之间的百分比差异?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个年度数据框架,每年有三个参数:年度、类型和值。我正试图计算占空比的百分比。例如,2014年总共有50个空的和50个取的-因此,如最终的_df所示,50%的空的和50%的取的 df 最终测向 year Empty Taken 0 2014 50 50 0 2013 ... ... 0 2012 ... ... 我是否应该将

我有一个年度数据框架,每年有三个参数:年度、类型和值。我正试图计算占空比的百分比。例如,2014年总共有50个空的和50个取的-因此,如最终的_df所示,50%的空的和50%的取的

df

最终测向

    year    Empty          Taken
            
0   2014    50             50 
0   2013    ...            ...    
0   2012    ...            ... 
我是否应该将单元格上移并进行百分比计算或任何其他方法?

您可以使用pivot\u table:

这让你:

res
      year  Empty  Taken
0     2014     50     50
1     2013    100   1900
2     2012     45      5
然后你可以得到每列的百分比:

total = (res['Empty'] + res['Taken'])
for col in ['Empty','Taken']:
    res[col+'_perc'] = res[col] / total


year  Empty  Taken  Empty_perc  Taken_perc                                     
2014     50     50        0.50        0.50
2013    100   1900        0.05        0.95
2012     45      5        0.90        0.10
您可以使用pivot_表:

这让你:

res
      year  Empty  Taken
0     2014     50     50
1     2013    100   1900
2     2012     45      5
然后你可以得到每列的百分比:

total = (res['Empty'] + res['Taken'])
for col in ['Empty','Taken']:
    res[col+'_perc'] = res[col] / total


year  Empty  Taken  Empty_perc  Taken_perc                                     
2014     50     50        0.50        0.50
2013    100   1900        0.05        0.95
2012     45      5        0.90        0.10

正如@sophods所指出的,您可以使用pivot_表重新设置数据帧的范围,以添加到他的答案中;我认为您追求的是百分比,因此我建议您保留“总计”记录,然后应用您的计算:

#pivot your data
res = (df.pivot_table(index='year',columns='type',values='value')).reset_index()
#calculate percentages of empty and taken
res['Empty'] = res['Empty']/res['Total']
res['Taken'] = res['Taken']/res['Total']
#final dataframe
res = res[['year', 'Empty', 'Taken']]

正如@sophods所指出的,您可以使用pivot_表重新设置数据帧的范围,以添加到他的答案中;我认为您追求的是百分比,因此我建议您保留“总计”记录,然后应用您的计算:

#pivot your data
res = (df.pivot_table(index='year',columns='type',values='value')).reset_index()
#calculate percentages of empty and taken
res['Empty'] = res['Empty']/res['Total']
res['Taken'] = res['Taken']/res['Total']
#final dataframe
res = res[['year', 'Empty', 'Taken']]

您可以筛选出类型为空和接收的记录,然后按年份分组并应用func。在func中,可以将类型设置为索引,然后获取所需的值并计算百分比。func中的x将是具有类型和值列以及每个组的数据的数据帧

 def func(x):
    x = x.set_index('type')
    total = x['value'].sum()
    return [(x.loc['Empty', 'value']/total)*100, (x.loc['Taken', 'value']/total)*100]

temp = (df[df['type'].isin({'Empty', 'Taken'})]
        .groupby('year')[['type', 'value']]
        .apply(lambda x: func(x)))
temp

year
2012    [90.0, 10.0]
2013    [5.0, 95.0] 
2014    [50.0, 50.0]
dtype: object
将结果转换为所需的数据帧

pd.DataFrame(temp.values.tolist(), index=temp.index, columns=['Empty', 'Taken'])
       Empty    Taken
year        
2012    90.0    10.0
2013    5.0     95.0
2014    50.0    50.0

您可以筛选出类型为空和接收的记录,然后按年份分组并应用func。在func中,可以将类型设置为索引,然后获取所需的值并计算百分比。func中的x将是具有类型和值列以及每个组的数据的数据帧

 def func(x):
    x = x.set_index('type')
    total = x['value'].sum()
    return [(x.loc['Empty', 'value']/total)*100, (x.loc['Taken', 'value']/total)*100]

temp = (df[df['type'].isin({'Empty', 'Taken'})]
        .groupby('year')[['type', 'value']]
        .apply(lambda x: func(x)))
temp

year
2012    [90.0, 10.0]
2013    [5.0, 95.0] 
2014    [50.0, 50.0]
dtype: object
将结果转换为所需的数据帧

pd.DataFrame(temp.values.tolist(), index=temp.index, columns=['Empty', 'Taken'])
       Empty    Taken
year        
2012    90.0    10.0
2013    5.0     95.0
2014    50.0    50.0

谢谢,但我需要%ValuesHanks中的数据,但我需要%values中的数据