我有一个样本数据集:
import pandas as pd
d = {
'ID': ['ID-1','ID-1','ID-1','ID-1','ID-2','ID-2','ID-2'],
'OBR':[100,100,100,100,200,200,200],
'OBX':['A','B','C','D','A','B','C'],
'notes':['hello','hello2','','','bye','',''],
}
df = pd.DataFrame(d)
它看起来像:
ID OBR OBX notes
ID-1 100 A hello
ID-1 100 B hello2
ID-1 100 C
ID-1 100 D
ID-2 200 A bye
ID-2 200 B
ID-2 200 C
我想循环遍历每一行,对于每个ID,OBR组合,给OBX和notes name分配一个数字,递增1,并相应地分配值。你知道吗
因此对于第一个ID,OBR combo:ID和OBR name保持不变,因为有4个不同的OBX值,OBX的名称将是OBX1、OBX2、OBX3和OBX4,因为有2个不同的notes值,notes的名称将是note1和note2。你知道吗
第二个ID,OBR combo:ID和OBR name保持不变,因为有3个不同的OBX值,OBX的名称将是OBX1、OBX2和OBX3,因为有1个notes值,notes的名称将是note1。你知道吗
期望输出:打印并分配值
ID = ID-1
OBR= 100
OBX1=A
OBX2=B
OBX3=C
OBX4=D
note1 = hello
note2 = hello2
ID = ID-2
OBR= 200
OBX1 = A
OBX2 = B
OBX3 = C
note1 = bye
我的尝试:
count = 0
grouped = df.groupby(['ID','OBR'])
for a, group in grouped:
ID = a[0]
OBR = a[1]
OBX+str(count) = group['OBX'] #this gives an error, can't use OBX+str(count) as the name
note+str(count) = group['notes'] #this gives an error as well
count +=1 #Is using count correct?
print(....)
一种方法是
groupby
到元组:然后用
enumerate
迭代行(如果适用):结果:
相关问题 更多 >
编程相关推荐