熊猫分组计算百分比变化列

时间:2018-08-20 02:23:41

标签: python python-2.7 pandas pandas-groupby percentage

我是熊猫数据框的新手,我需要帮助来了解百分比变化。

我确实从查询生成了一个csv,以便通过为列分配排名来计算平均值。

rank       ds         continent           region      device     traffic
1          08/13      North america         US        mobile      7300
1          08/13      North america         US        desktop     2500
2          08/06       Europe               UK        mobile      3300
2          08/06       Europe              Italy      desktop     5600

然后,我确实在第二个CSV中计算了“ 1周”和“ 3周”的平均点击量。

df_1 = df.loc[df['rank'] == '1']
df_1['traffic'] = df_1['traffic'].astype(float).fillna(0)
avg_1 = df_1.groupby(['continent','region','device']).mean()
avg_1['ds'] = '1 week'

last_3 = df.loc[df['rank'].isin(['2','3','4'])]
last_3['traffic'] = last_3['traffic'].astype(float).fillna(0)
avg_3 = last_3.groupby(['continent','region','device']).mean()
avg_3['ds'] = '3 week'  

最终平均值输出:

market               country       traffic       device          ds
North america         US           36015.33      mobile        1week
North america         US           40663.67      desktop       3week
Europe                UK           360270.7      mobile        1week 
Europe                Italy        1363183       desktop       3week

有人可以帮我计算1周和3周的变化流量百分比吗?谢谢!

1 个答案:

答案 0 :(得分:0)

明白了这一点。使用了pct_change()