Python3.7 Pandas1.0.1数据帧计算范围内列的总和并重新分组为一个新行?

2024-09-30 04:32:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我关于StackOverflow的第一个问题。请善待我:)

您好,我刚刚开始了一个关于数据科学的小项目,我想通过matplot最终创建一个饼图,显示设备型号在网站总流量中的百分比(即30%的iPhone、20%的iPad、10%的Mac等)

useragent count
iPhone    11298
Mac        3206
iPad        627
SM-N960F    433
SM-N950F    430
...         ...
K330          1
K220          1
SM-J737P      1
SM-J737T1     1
0PFJ50        1
[1991 rows x 2 columns]

从截图上看,有1991年的记录。 我正在准备用于绘图的数据,我只想显示前5个UserAgent(前4个是设备,前5个将标记为其他和剩余项目的总和)

预期输出如下所示:

useragent count
iPhone    11298
Mac        3206
iPad        627
SM-N960F    433
Others     9000

非常感谢你


Tags: 数据项目网站maccount科学stackoverflowuseragent
2条回答

使用:

#first sorting data if necessary
df1 = df.sort_values('count', ascending=False)

#then get top 4 rows
df2 = df1.head(4)
#filter column `count` for all values after 4 rows
summed = df1.loc[df1.index[4:], 'count'].sum()

#create DataFrame by another counts
df3 = pd.DataFrame({'useragent':['Other'], 'count':[summed]})

#join together
df4 = pd.concat([df2, df3], sort=False, ignore_index=True)
print (df4)
  useragent  count
0    iPhone  11298
1       Mac   3206
2      iPad    627
3  SM-N960F    433
4     Other    435

编辑:

#filter by threshold
mask = df['count'] > 500
#filtered rows by boolean indexing
df2 = df[mask]
#inverted mask - sum by count
summed = df.loc[~mask, 'count'].sum()
#same like above
df3 = pd.DataFrame({'useragent':['Other'], 'count':[summed]})

df5 = pd.concat([df2, df3], sort=False, ignore_index=True)
print (df5)
  useragent  count
0    iPhone  11298
1       Mac   3206
2      iPad    627
3     Other    868

您可以尝试以下方法:

# sort dataframe
df.sort_values(by=['count'], inplace=True)
# recreate the index of your rows to make sure that 0 corresponds to the one with the higher count
df.reset_index(drop=True, inplace=True)
# add your new row to your dataset
df.append({'useragent': 'Others', 'count': df.loc[5:]['count'].cumsum()}, inplace=True)
# drop the rows you don't need anymore
df.drop([5:len(df.index.values.tolist())-1], inplace=True)

虽然我不能完全确定,但值得一试。我希望它能给你们一些想法

相关问题 更多 >

    热门问题