How to make same value of one column for those rows which have same values in another column pandas

Viewed 834

I have a pandas dataframe where some of the rows in a column named 'Case_num' have the same value. I want to fill the column named 'Work_Hrs' with a sum of the non-zero values in that column if 'Case_num' is the same. For example, the input data is:

enter image description here

I want to fill the column 'Work_Hrs' with a sum of non zero values, i.e. 6 in this case, see below:

Output is:

Thank you.

1 Answers

You can try the following: I have created a similar sample:

dic={'Work':[0,1,2,4,1],'Case_Num':[1,1,1,3,3]}
df=pd.DataFrame(dic)

   Work Case_Num
0   0   1
1   1   1
2   2   1
3   4   3
4   1   3

Grouping by the column and apply sum on target column

sum_series=df.groupby('Case_Num')['Work'].sum()
Case_Num
1    3
3    5
Name: Work, dtype: int64

And then create function to apply on dataframe

def change_value(case,work):
if work==0:
    work=sum_series[case]
return work

df['Work']=df.apply(lambda x: change_value(x['Case_Num'],x['Work']),axis=1)

Output:

   Work Case_Num
0   3   1
1   1   1
2   2   1
3   4   3
4   1   3

Update For changing Work column with sum everywhere, you can use following

df['Work']=df['Case_Num'].apply(lambda x: sum_series[x])

Hope it helps.

Related