python - 如何使用group by获得唯一ID的累积和?

标签 python pandas data-processing

我对 python 和 pandas 非常陌生,正在处理 pandas 数据框,看起来像

Date     Time           ID   Weight
Jul-1     12:00         A       10
Jul-1     12:00         B       20
Jul-1     12:00         C       100
Jul-1     12:10         C       100
Jul-1     12:10         D       30
Jul-1     12:20         C       100
Jul-1     12:20         D       30
Jul-1     12:30         A       10
Jul-1     12:40         E       40
Jul-1     12:50         F       50
Jul-1     1:00          A       40

我正在尝试按日期、时间和 ids 进行分组,并应用累积总和,这样如果下一个时间段中存在 id,则权重仅添加一次(唯一)。生成的数据框将如下所示

Date     Time           Weight   
Jul-1     12:00         130     (10+20+100)
Jul-1     12:10         160     (10+20+100+30)
Jul-1     12:20         160     (10+20+100+30)
Jul-1     12:30         160     (10+20+100+30)
Jul-1     12:40         200     (10+20+100+30+40)
Jul-1     12:50         250     (10+20+100+30+40+50)
Jul-1     01:00         250     (10+20+100+30+40+50)

这是我在下面尝试的,但这仍然多次计算权重:

df=df.groupby(['date','time','ID'])['Wt'].apply(lambda x: x.unique().sum()).reset_index()
df['cumWt']=df['Wt'].cumsum()

任何帮助将不胜感激!

提前非常感谢!!

最佳答案

下面的代码使用pandas.duplicate() , pandas.merge() , pandas.groupby/sumpandas.cumsum()达到所需的输出:

# creates a series of weights to be considered and rename it to merge
unique_weights = df['weight'][~df.duplicated(['weight'])]
unique_weights.rename('consider_cum', inplace = True)

# merges the series to the original dataframe and replace the ignored values by 0
df = df.merge(unique_weights.to_frame(), how = 'left', left_index=True, right_index=True)
df.consider_cum = df.consider_cum.fillna(0)

# sums grouping by date and time
df = df.groupby(['date', 'time']).sum().reset_index()

# create the cumulative sum column and present the output
df['weight_cumsum'] = df['consider_cum'].cumsum()
df[['date', 'time', 'weight_cumsum']]

产生以下输出:

enter image description here

关于python - 如何使用group by获得唯一ID的累积和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55051707/

相关文章:

java - 从 Java 进行数据处理的工具

Python:在迭代列表时从列表中删除元素,以及在范围内查找值的最有效方法

python - 字符串 "integers"到占 "non-numeric"字符串的整数的列表 Python

python - 更多关于 tkinter optionmenu 第一个选项消失

python - 创建两个 numpy.ndarray 的字典?

python - 从列名列表中删除 pandas 数据框中的列的快速方法是什么

python - 删除包含 2 个单词的引号并删除它们之间的逗号

python - python 中的缩放对数合并

python - 访问 python 子列表以导入 pandas DataFrame

python - 读取 json 文件作为输入并作为 pprint 输出?