我有一個包含四列的df:
col1 col2 col3 col4
0 2021-10-18 2021-10-27 2021-11-08 2021-11-21
1 2021-01-30 2021-02-01 2021-02-28 2021-03-18
2 2021-08-17 2021-08-20 2021-09-02 2021-09-07
我想計算列之間的作業日數。到目前為止,我這樣做了:
col1 = [d.date() for d in df['col1']]
col2 = [d.date() for d in df['col2 ']]
col3 = [d.date() for d in df['col3']]
col4 = [d.date() for d in df['col4 ']]
df['bday1'] = np.busday_count(col1, col2)
df['bday2'] = np.busday_count(col2, col3)
df['bday3'] = np.busday_count(col3, col4)
有沒有辦法更有效地做到這一點?例如,對于會有更多列的情況?我會很感激你的幫助!
uj5u.com熱心網友回復:
嘗試這個:
cols = ['col1', 'col2', 'col3', 'col4']
for i, (col1, col2) in enumerate(zip(cols[:-1], cols[1:])):
df[f'bday{i 1}'] = np.busday_count(
df[col1].dt.date.to_list(),
df[col2].dt.date.to_list(),
)
您只需要指定要使用的列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432179.html
