Key
鉴于Type
等于B
并将结果分配给each ,我如何获得 each 的值A
?我需要将此逻辑应用于具有许多不同组的大型数据框。
df = pd.DataFrame({'Key': [1, 2, 3, 4, 5],
'Group': ['Z', 'Z', 'Z', 'Z', 'Z'],
'Type': ['A', 'A', 'B', 'A', 'A'],
'Flag': [0, 0, 1, 0, 0]
})
预期结果:
expected = pd.DataFrame({'Key': [1, 2, 3, 4, 5],
'Group': ['Z', 'Z', 'Z', 'Z', 'Z'],
'Type': ['A', 'A', 'B', 'A', 'A',],
'parentKey': [3, 3, np.nan, 3, 3],
'Flag': [0, 0, 1, 0, 0]})
我一直在玩,transform
但我很困惑,没有靠近。
合并更容易:
df = pd.DataFrame({'Key': [1, 2, 3, 4, 5],
'Group': ['Z', 'Z', 'Z', 'Z', 'Z'],
'Type': ['A', 'A', 'B', 'A', 'A'],
'Flag': [0, 0, 1, 0, 0]
})
df_parent = df.loc[df['Type'] == 'B', ['Key', "Group"]].rename(columns={'Key':'parentKey'})
pd.concat([df[df['Type'] != 'B'].merge(df_parent, on = 'Group', how = 'left'), df.loc[df['Type'] == 'B']], ignore_index=True)
Key Group Type Flag parentKey
0 1 Z A 0 3.0
1 2 Z A 0 3.0
2 4 Z A 0 3.0
3 5 Z A 0 3.0
4 3 Z B 1 NaN
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句