gpt4 book ai didi

python - 循环遍历 groupby 为 pandas 中的名称分配数字

转载 作者:行者123 更新时间:2023-12-01 09:23:23 25 4
gpt4 key购买 nike

我有一个示例数据集:

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和注释名称分配一个数字,递增1并相应地分配值。

因此,对于第一个 ID、OBR 组合:ID 和 OBR 名称保持不变,因为有 4 个不同的 OBX 值,因此 OBX 的名称将是 OBX1、OBX2、OBX3 和 OBX4 ,并且由于有 2 个不同的音符值,因此音符的名称将为 note1 和 note2。

第二个 ID,OBR 组合:ID 和 OBR 名称保持不变,因为有 3 个不同的 OBX 值,所以 OBX 的名称将是 OBX1、OBX2 和 OBX3,并且因为有是 1 个音符值,则音符的名称为 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:

res = df.groupby(['ID', 'OBR'])\
.agg({'OBX': lambda x: tuple(x), 'notes': lambda x: tuple(filter(None, x))})\
.reset_index()

print(res)

ID OBR OBX notes
0 ID-1 100 (A, B, C, D) (hello, hello2)
1 ID-2 200 (A, B, C) (bye,)

然后迭代行,在适用的情况下使用enumerate:

for row in res.itertuples():
print('\nID =', row.ID)
print('OBR =', row.OBR)
for i, obx in enumerate(row.OBX, 1):
print('OBX'+str(i)+' =', obx)
for i, note in enumerate(row.notes, 1):
print('notes'+str(i)+' =', note)

结果:

ID = ID-1
OBR = 100
OBX1 = A
OBX2 = B
OBX3 = C
OBX4 = D
notes1 = hello
notes2 = hello2

ID = ID-2
OBR = 200
OBX1 = A
OBX2 = B
OBX3 = C
notes1 = bye

关于python - 循环遍历 groupby 为 pandas 中的名称分配数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50628327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com