【问题标题】:Referencing rows recursively in Dataframe在Dataframe中递归引用行
【发布时间】:2019-01-05 22:04:28
【问题描述】:

Dataframedf定义如下:

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

只要A 列是False,但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

【问题讨论】:

    标签: python pandas python-2.7 dataframe


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      我猜这不是最优的,但至少它有效。

      df1['to_move'] = ((df1['A']==False) & (df1['B']>0))
      indexes_to_move = list(df1[df1['to_move']].index)
      for ind in indexes_to_move:
          temp = df1.loc[ind:,'B']
          to_change = temp[temp==0].index.min()
          df1.loc[ind, 'A'] = True
          df1.loc[to_change, 'A'] = False
      del df1['to_move']
      

      【讨论】:

      • 不知何故我没有得到想要的输出。你也一样吗?
      猜你喜欢
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 2014-06-30
      相关资源
      最近更新 更多