【问题标题】:How to save rows when value change in column pythonpython - 列python中的值更改时如何保存行
【发布时间】:2019-11-11 06:39:27
【问题描述】:

我有DataFrame 有两列IDValue1,我想在列 value1 列的值发生变化时选择行。我想保存更改前的第 3 行和更改后的第 3 行,还要更改点行。

df=pd.DataFrame({'ID':[1,3,4,6,7,8,90,23,56,78,90,34,56,78,89,34,56],'Value1':[0,0,0,0,0,2,2,2,2,0,0,0,1,1,1,1,1]})

 ID  Value1
0    1       0
1    3       0
2    4       0
3    6       0
4    7       0
5    8       2
6   90       2
7   23       2
8   56       2
9   78       0
10  90       0
11  34       0
12  56       1
13  78       1
14  89       1
15  34       1
16  56       1


output:

    ID  Value1
0    4       0
1    6       0
2    7       0
3    8       2
4   90       2
5   23       2
6   90       2
7   23       2
8   56       2
9   78       0
10  90       0
11  34       0

【问题讨论】:

    标签: python-3.x pandas numpy pandas-groupby


    【解决方案1】:

    IIUC,

    import numpy as np
    
    df=pd.DataFrame({'ID':[1,3,4,6,7,8,90,23,56,78,90,34,56,78,89,34,56],'Value1':[0,0,0,0,0,2,2,2,2,0,0,0,1,1,1,1,1]})
    df.reset_index(drop=True) #index needs to start from zero for solution
    ind = list(set([val for i in df[df['Value1'].diff()!=0].index for val in range(i-3, i+4) if i>0 and val>=0])) 
    # diff gives column wise differencing. combined it with nested list and 
    # finally, list(set()) to drop any duplicates in index values
    
    df[df.index.isin(ind)]
       ID   Value1
    2   4   0
    3   6   0
    4   7   0
    5   8   2
    6   90  2
    7   23  2
    8   56  2
    9   78  0
    10  90  0
    11  34  0
    12  56  1
    13  78  1
    14  89  1
    15  34  1
    

    如果您想保留重复的出现,请将 list(set()) 函数放在列表上

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      相关资源
      最近更新 更多