首页 > 解决方案 > 每隔一行更改一次值 - 熊猫

问题描述

我的目标是更改熊猫 df 中每隔一行的值。使用下面,我希望在Group. 每组中的两行将Group始终重复。但是,发生这种情况的方式是随机的。例如,我不会每隔一行将其更改为特定值。它改变的方法取决于上一行中的值。

具体来说,每组行将包含来自GR1或的唯一值GR2。我希望将第二个值更改为Group第一个值不是的值。所以在下面使用,第一行将是AB。因此,后续行将是相反的值。

注意: 的每个周期只有两个重复的行Time。此外,内部的唯一值GR1GR2将根据数据集的不同而有所不同,所以我希望能解释这一点。

df = pd.DataFrame({      
    'Time' : [1,1,2,2,3,3,4,4],    
    'GR1' : ['A','A','A','A','A','A','A','A'],
    'GR2' : ['B','B','B','B','B','B','B','B'],
    'Group' : ['A','A','B','B','B','B','A','A'],    
   })

GR1 = df['GR1'].unique()
GR2 = df['GR2'].unique() 

groups = [y for x in [GR1, GR2] for y in x] 

df['Group'] = np.where(df.index % 2, groups[0], groups[1])

东风:

   Time GR1 GR2 Group
0     1   A   B     A 
1     1   A   B     A # first row is from GR1 so this row is GR2
2     2   A   B     B 
3     2   A   B     B # first row is from GR2 so this row is GR1
4     3   A   B     B 
5     3   A   B     B # first row is from GR2 so this row is GR1
6     4   A   B     A 
7     4   A   B     A # first row is from GR1 so this row is GR2

出去:

   Time GR1 GR2 Group
0     1   A   B     B
1     1   A   B     A
2     2   A   B     B
3     2   A   B     A
4     3   A   B     B
5     3   A   B     A
6     4   A   B     B
7     4   A   B     A

预期输出:

   Time GR1 GR2 Group
0     1   A   B     A
1     1   A   B     B
2     2   A   B     B
3     2   A   B     A
4     3   A   B     B
5     3   A   B     A
6     4   A   B     A
7     4   A   B     B

标签: pythonpandas

解决方案


这个想法是为最后三列中的每一列获取第二行,根据您的逻辑进行比较,然后用逻辑的结果替换原始数据框。

DT = df.copy()

DT.iloc[1::2, -1] = np.nan 

# the second rows will be filled with the values from the previous row
DT = DT.ffill()

In [252]: gr1 = DT.iloc[1::2, 1]

In [253]: gr2 = DT.iloc[1::2, 2]

In [258]: check = DT.iloc[1::2, -1]
 
In [260]: bool1 = gr1==check

In [261]: bool2 = gr2==check

In [264]: condlist = [bool1, bool2]

In [265]: choicelist = [gr2, gr1]

In [267]: DT.iloc[1::2, -1] = np.select(condlist, choicelist)

In [268]: DT
Out[268]: 
   Time GR1 GR2 Group
0     1   A   B     A
1     1   A   B     B
2     2   A   B     B
3     2   A   B     A
4     3   A   B     B
5     3   A   B     A
6     4   A   B     A
7     4   A   B     B

推荐阅读