在数据框中递归引用行

时间:2019-01-05 22:04:28

标签: python pandas python-2.7 dataframe

数据帧df的定义如下:

import pandas as pd
df1 = pd.DataFrame({'A':[False,True,True,False,True,True,True,True,False,True,True], 'B':[0,0,0,2,2,1,0,0,1,0,0]}, columns=['A','B'])
df1
        A  B
0   False  0
1    True  0
2    True  0
3   False  2
4    True  2
5    True  1
6    True  0
7    True  0
8   False  1
9    True  0
10   True  0

只要列AFalse但列B中的值是>0,则False应该移到下一行,直到B0。因此,上述数据框的期望输出是

        A  B
0   False  0
1    True  0
2    True  0
3    True  2
4    True  2
5    True  1
6   False  0
7    True  0
8    True  1
9   False  0
10   True  0

2 个答案:

答案 0 :(得分:1)

IIUC

s=(~df1.A).cumsum() 
# get the group key 

groupkey=df1.groupby(s).B.transform('first')>0
# find whether we should include the group when the first B of the group is great than 0 or not

df1.A.update(df1.loc[groupkey&(~(df1.B.gt(0)&(df1.A))),'A'].groupby(s).shift().fillna(True)) 
# using update 
df1
        A  B
0   False  0
1    True  0
2    True  0
3    True  2
4    True  2
5    True  1
6   False  0
7    True  0
8    True  1
9   False  0
10   True  0

更多信息

~(df1.B.gt(0)&(df1.A)) # exclude those A equal to True and B great than 0 row
0      True
1      True
2      True
3      True
4     False
5     False
6      True
7      True
8      True
9      True
10     True
dtype: bool

答案 1 :(得分:0)

我猜这不是最佳选择,但至少可以奏效。

<!DOCTYPE html>
<html>
    <body>
        <hr id="line" />

        <script>
        var element = document.getElementById('line')
        var c = document.createElement('input')
        c.setAttribute("type", "checkbox")
        c.checked = true

        c.onclick = function(){
            if(c.checked) element.style.display = 'block'
            if(c.checked == false) element.style.display = 'none'
        }

        /* This code below saves the state of the checkbox,
         but never fires the event or updates the element */

        // c.checked = (localStorage.getItem('cchecked')== 'true');
        if (localStorage.getItem('cchecked')== 'true') {
            c.checked = true;

        }
        else if (localStorage.getItem('cchecked')== 'false') {
            c.checked = false;

        }

        c.onchange = function(){
            localStorage.setItem('cchecked', ( c.checked ? 'true' : 'false'))
        }

        if ( !c.checked) element.style.display = 'none'

        document.body.appendChild(c);
        </script>

    </body>

</html>