You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于条件合并设备类别会话数生成新DataFrame?

解决DataFrame设备类别合并问题

没问题,这事儿用pandas处理起来很简单,我给你两种实用的方案,你可以根据自己的需求选:

方案一:类别映射 + 分组聚合(简洁高效)

这种方法通过先把tablet类别映射为desktop,再按时间和设备类别分组求和,一步到位完成合并和筛选:

import pandas as pd

# 假设你的原始DataFrame名为df
# 1. 创建设备类别映射字典:tablet转成desktop,其他保持原样
device_map = {'tablet': 'desktop', 'desktop': 'desktop', 'mobile': 'mobile'}

# 2. 生成新的设备类别列
df['new_deviceCategory'] = df['deviceCategory'].map(device_map)

# 3. 按year、month和新设备类别分组,对sessions求和
result_df = df.groupby(['year', 'month', 'new_deviceCategory'], as_index=False)['sessions'].sum()

# 4. 重命名列名(可选,恢复原来的列名)
result_df.rename(columns={'new_deviceCategory': 'deviceCategory'}, inplace=True)

方案二:分步处理(更直观)

如果想更清晰地看到每一步的操作,可以拆分步骤:

import pandas as pd

# 1. 提取desktop和mobile的原始数据
desktop_mobile = df[df['deviceCategory'].isin(['desktop', 'mobile'])].copy()

# 2. 提取tablet的数据,将设备类别改为desktop
tablet_data = df[df['deviceCategory'] == 'tablet'].copy()
tablet_data['deviceCategory'] = 'desktop'

# 3. 合并所有数据,然后按year、month、deviceCategory分组求和
combined_df = pd.concat([desktop_mobile, tablet_data], ignore_index=True)
result_df = combined_df.groupby(['year', 'month', 'deviceCategory'], as_index=False)['sessions'].sum()

两种方法最终都会得到你想要的结果:只保留desktop和mobile类别,且tablet的sessions已经合并到对应时间的desktop数据里。

内容的提问来源于stack exchange,提问作者nississippi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:59:05