简体   繁体   中英

How can I slice one column in a dataframe to several series based on a condition

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

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.

Does anyone have any ideas to do this?

Thanks in advance!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM