社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python3.7pandas1.0.1dataframe-计算一个范围内列的和并重新组合为一个新行?

Visiony10 • 5 年前 • 1504 次点击  

我关于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个用户代理(前4个是设备,前5个将被标记为其他和剩余项目的总和)。

预期输出如下:

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

非常感谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56349
 
1504 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Sacha Bernheim
Reply   •   1 楼
Sacha Bernheim    5 年前

你可以试试这样的方法:

# 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)

我不完全确定,但值得一试。我希望它能给你一些建议。

jezrael
Reply   •   2 楼
jezrael    5 年前

使用:

#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