python 组合数据框中的行并将值相加

2024-01-20

我有一个数据框:

 Type:  Volume:
 Q     10
 Q     20 
 T     10 
 Q     10
 T     20
 T     20
 Q     10

我想将类型 T 合并到一行中,并且仅当两个(或更多) T 连续时才添加音量

即:

 Q    10
 Q    20 
 T    10 
 Q    10 
 T    20+20=40
 Q    10

有什么办法可以实现这一点吗?会DataFrame.groupby work?


我认为这会有所帮助。此代码可以处理任意数量的连续“T”,您甚至可以更改要组合的字符。我在代码中添加了注释来解释它的作用。

https://pastebin.com/FakbnaCj https://pastebin.com/FakbnaCj

import pandas as pd

def combine(df):
    combined = [] # Init empty list
    length = len(df.iloc[:,0]) # Get the number of rows in DataFrame
    i = 0
    while i < length:
        num_elements = num_elements_equal(df, i, 0, 'T') # Get the number of consecutive 'T's
        if num_elements <= 1: # If there are 1 or less T's, append only that element to combined, with the same type
            combined.append([df.iloc[i,0],df.iloc[i,1]])
        else: # Otherwise, append the sum of all the elements to combined, with 'T' type
            combined.append(['T', sum_elements(df, i, i+num_elements, 1)])
        i += max(num_elements, 1) # Increment i by the number of elements combined, with a min increment of 1
    return pd.DataFrame(combined, columns=df.columns) # Return as DataFrame

def num_elements_equal(df, start, column, value): # Counts the number of consecutive elements
    i = start
    num = 0
    while i < len(df.iloc[:,column]):
        if df.iloc[i,column] == value:
            num += 1
            i += 1
        else:
            return num
    return num

def sum_elements(df, start, end, column): # Sums the elements from start to end
    return sum(df.iloc[start:end, column])

frame = pd.DataFrame({"Type":   ["Q", "Q", "T", "Q", "T", "T", "Q"],
               "Volume": [10,   20,  10,  10,  20,  20,  10]})
print(combine(frame))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python 组合数据框中的行并将值相加 的相关文章

随机推荐

  • 无法使用 AKS 和 ACR 提取新映像

    我突然在使用 AKS 从 Azure 容器注册表中提取最新映像时遇到问题 之前工作正常 If I run kubectl describe pod
  • CodeIgniter htaccess 修改为半 https 且无 www 版本

    htaccess 修改与核心 PHP 中不同 因此 经过一番搜索 我得到了以下代码 在那之前 我的要求是我的项目的标准 整个网站严禁使用 www 即直接重定向到非 www 版本 HTTPS 适用于某些页面 结帐 登录页面 其他页面严格采用
  • Android 自定义对话框的昏暗背景

    正如标题所示 我似乎无法调暗我制作的自定义对话框的背景 网上无数的解决方案都提到了下面第一个片段中的最后 3 行代码 这对对话框的 UI 没有影响 请看下面的代码 Dialog dialog new Dialog MainActivity
  • iOS SDK中逐行读取文件

    我有一个文本文件如下 line1 line2 line3 line4 line5 我想从文件读入两个字符串数组 以便line1 line3 line 5 进入array1 and line 2 line 4 line 6 进入array2
  • 将 ISO 8601 日期时间字符串反序列化为 C# DateTime

    我正在尝试使用 JsonConvert DeserializeObject
  • 按钮动画像ios游戏中心按钮

    我正在尝试让我的按钮像 ios 游戏中心中的按钮一样具有动画效果 它们似乎像气泡一样在屏幕上摇摆和漂浮 我尝试过在屏幕上随机移动按钮 使它们同时以恒定的圆形路径移动 但效果不一样 我需要一种摇摆效果 任何想法表示赞赏 结合几个CAKeyfr
  • Scenebuilder 2.0 中的自定义组件

    在 Scenebuilder 1 1 中 您可以将整个自定义组件作为一个整体导入 然而 在 2 0 中 它将组件作为单独的部分 容器和节点 导入 由于我的自定义组件依赖于与其控制器和 ID 的统一工作 因此这会破坏它 到目前为止我能做些什么
  • 动态编译依赖于特定类加载器加载的类的java代码

    我们有能力即时动态编译 Java 代码 我至少知道Java 运行时编译器 https github com OpenHFT Java Runtime Compiler and 内存Java编译器 https github com trung
  • WCErrorCodeDeliveryFailed:无法交付有效负载

    我正在开发一款在 iPhone 和 Apple Watch 之间共享数据的应用程序 使用WCSession方法sendMessage replyHandler errorHandler 实施该方法后 我收到如下错误 WCSession on
  • GitHub SSH 密钥声称未使用

    为什么 在我的 GitHub 帐户上的 设置 gt SSH 密钥 下 它显示 由 GitHub for Mac 于 2014 年 10 月 24 日添加 从未使用过 没用过 我用过 我的个人资料中显示了很多贡献 从that机器 我还有另一把
  • Android:使用 onTouchListener() 循环执行线程

    您好 我的应用程序中有 8 个按钮 每个按钮都配置为 onclickListener 当单击该按钮时 字符串将写入套接字 现在我希望当我按住按钮时 字符串必须循环写入 这就是我正在尝试做的事情 bLeft setOnTouchListene
  • 在 Ubuntu 上安装 Java 7

    Note 这个问题是在 Oracle 将 OpenJDK 作为 Oracle JDK 的免费版本之前提出的 历史答案反映了这一点 从 2022 年起 您不应使用 Java 7 除非您必须使用无法在 OpenJDK 8 上运行的项目 为了安装
  • ELK 未将元数据从 filebeat 传递到 Logstash

    通过以下方式安装 ELK 服务器 https www digitalocean com community tutorials how to install elasticsearch logstash and kibana elk sta
  • R 编程:从数据框中查找所有因子

    我正在尝试获取数据框列的类类型 我正在做的是 sapply mydata class 但现在 我只想找到那些作为因素的列名 我尝试了以下方法 sapply data is factor 但它给了我 ResponseFlag Gender M
  • ANTLR 隐式乘法

    我是 ANTLR 的新手 我正在尝试扩展所提供的简单计算器的示例here https stackoverflow com a 1932664 具体来说 我尝试添加一些简单的函数 负数等 以熟悉 ANTLR 然而 我在尝试实现 隐式 乘法时遇
  • 如何收集与输入函数匹配通配符的Snakemake输入文件?

    我有一组使用 BWA MEM 生成并使用 GATK IndelRealigner 等进一步处理的 BAM 文件 我正在以较小的块对 BAM 文件进行预处理 以加快处理速度 然而 我必须在变体调用之前将这些单独的文件合并到一个 BAM 文件中
  • 为什么我不能从互斥锁中可变地借用单独的字段? [复制]

    这个问题在这里已经有答案了 尝试通过以下方式获取对单独字段的可变引用MutexGuard struct MyObject pub a i32 pub b i32 fn func 1 mtx Mutex
  • x86_64 执行 Shellcode 失败:

    我在 64 位 Linux 上使用 Python 2 7 我有以下 Python 脚本 应该执行一个简单的 Hello World shellcode import urllib2 import ctypes shellcode xb8 x
  • Dynamic_cast 不适用于非多态类型的原因

    有课B和派生类D class B int b class D public B int d D d new D B b dynamic cast
  • python 组合数据框中的行并将值相加

    我有一个数据框 Type Volume Q 10 Q 20 T 10 Q 10 T 20 T 20 Q 10 我想将类型 T 合并到一行中 并且仅当两个 或更多 T 连续时才添加音量 即 Q 10 Q 20 T 10 Q 10 T 20 2