Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This is my simple dataframe

    Name    balans  overdue  loan
0   Branch1  125      2500   4200
1   Branch1  154      500    8500
2   Branch2  125      600    2300
3   Branch3  154      433    5600
4   Branch3  130      0      5000   
5   Branch4  152      630    9800
6   Branch4  129      123    6500
7   Branch5  130      0      1235
7   Branch5  152      75     1897

I'm trying to find a solution to this if Balans column is equal to 154 then delete overdue value from that row and add to overdue where balans is 125 in the same Branch, if there are multiple 125 in one Branch, then add it to first come or with random, it just needs to be in the same branch. Same as with other Balans values, for example 154->125, 152 -> 130.

I don't know how to solve this. Could you help me please. Any help would be appreciated. Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
144 views
Welcome To Ask or Share your Answers For Others

1 Answer

Maybe this could work?

def func(group):
  map = {154:125, 152:130}
  values = {}
  for k,v in map.items():
    q = group.query(f'balans=={v}')
    if len(q):
      values[k] = q.iloc[0].overdue
  return group.apply(lambda x: x.overdue if x.balans not in values else values[x.balans], axis=1)

df.loc[:,'overdue'] = df.group_by('Name').apply(func).values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...