如何根据条件将数据框中的一列切片为多个系列 [英] How can I slice one column in a dataframe to several series based on a condition

查看:73
本文介绍了如何根据条件将数据框中的一列切片为多个系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据框:

I have a data frame that looks like this:

       'A' diff('A')
    0   1    NaN
    1   2     1
    2   5     3
    3   2    -3
    4   4     2
    5   6     2
    6   1    -5
    7   7     6
    8   9     2

我想获得的是这样的东西:

What I would like to obtain is something like this:

       'B'
    0   1
    1   2
    2   5

       'C'
    0   2
    1   4
    2   6

       'D'
    0   1
    1   7
    2   9

我想将'A'列切成几个新列;切片原始列的条件是,列 diff('A')上的值是负数.我当时认为迭代器应该遍历数据帧,并且只要它在 diff('A')中遇到负值,就应该对该列进行切片并将其传递给Series,然后继续进行操作,直到它到达列的末尾.

I would like to slice the column 'A' into several new columns; the condition to slice the original column is that value on the column diff('A') is negative. I was thinking that an iterator should go through the dataframe and, whenever it encounters a negative value in diff('A'), it should slice the column and pass it to a Series, and then continue until it reaches the end of the column.

有人有什么想法吗?

提前谢谢!

推荐答案

我相信您的想法很好,但是使用pandas内置选择器会更有效:

I believe your idea works fine, but it will be more efficient to use the pandas built-in selector:

decreased_value = df[df['diff'] < 0]['A'].reset_index(drop=True)

这篇关于如何根据条件将数据框中的一列切片为多个系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆