Python 根据每N行的第一次出现修改列值,如有必要
我有一个这样的数据帧Python 根据每N行的第一次出现修改列值,如有必要,python,pandas,Python,Pandas,我有一个这样的数据帧 ID,A,B 1,Fruit,Orange 1,Fruit,Apple 3,Fruit,Mango 4,Fruit,Banana 5,Fruit,PineApple 5,Fruit,Grapes 我想每3行修改一次,使它们有一个公共ID。我想应用的ID是每3行出现的第一个ID 产出将是 ID,A,B 1,Fruit,Orange 1,Fruit,Apple 1,Fruit,Mango 4,Fruit,Banana 4,Fruit,PineApple 4,Fruit,Gra
ID,A,B
1,Fruit,Orange
1,Fruit,Apple
3,Fruit,Mango
4,Fruit,Banana
5,Fruit,PineApple
5,Fruit,Grapes
我想每3行修改一次,使它们有一个公共ID。我想应用的ID是每3行出现的第一个ID
产出将是
ID,A,B
1,Fruit,Orange
1,Fruit,Apple
1,Fruit,Mango
4,Fruit,Banana
4,Fruit,PineApple
4,Fruit,Grapes
你能建议,我怎样才能做到这一点 与整数除法创建的组一起使用:
#if default RangeIndex
#df['ID'] = df.groupby(df.index // 3)['ID'].transform('first')
#general solution
df['ID'] = df.groupby(np.arange(len(df)) // 3)['ID'].transform('first')
print (df)
ID A B
0 1 Fruit Orange
1 1 Fruit Apple
2 1 Fruit Mango
3 4 Fruit Banana
4 4 Fruit PineApple
5 4 Fruit Grapes
详细信息:
print (np.arange(len(df)) // 3)
[0 0 0 1 1 1]