简体   繁体   中英

how to add new colume from original dataframe column - python)

I want to add a new column with calcuation using data condition from original one.

data that I am using looks like ; enter image description here

I wnat to calcuate number under the duration tap using 'type' columes, and the outcome that i am expecting would be --

 team        date        (core-work/corework-duration)
resolution   2021-09-01   0.9043
resolution   2021-09-02   0.9385

I have been reasearching how to solove that issue, but I lost..... please help me out thanks in advance.

Given the following example:

df = pd.DataFrame({'Team':['Resolution', 'Resolution', 'Resolution', 'Resolution'], 
                   'date':['2021-09-01', '2021-09-01', '2021-09-02', '2021-09-02'], 
                   'Type':['Core-work', 'available', 'Core-work', 'available'], 
                   'duration': [218394, 23102, 225850, 14800]})
print(df)
         Team        date       Type  duration
0  Resolution  2021-09-01  Core-work    218394
1  Resolution  2021-09-01  available     23102
2  Resolution  2021-09-02  Core-work    225850
3  Resolution  2021-09-02  available     14800

Divide 'Core-work' duration by the sum of the durations for each Team-date group:

frac_df = df[df['Type'].eq('Core-work')].set_index(['Team', 'date'])[['duration']].div(df.groupby(['Team', 'date']).sum())

print(print(frac_df.reset_index()))
         Team        date  duration
0  Resolution  2021-09-01  0.904338
1  Resolution  2021-09-02  0.938500

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM