Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

python - How to transfer values from row to another row with condition

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!


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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...