簡體   English   中英

在帶有“季節”(季節1,季節2 ...)列的熊貓DF中,需要將6個月或~182天添加到不為空的最后一個季節

[英]in a pandas DF with 'season' (season1, season2...) columns, 6 months or ~182 days needs to be added to the last season that's not null

我有一個有多個季節的熊貓 DF,對於每一行,我需要將 6 個月(~182 天)添加到不為空的上一季。日期是 dtype dtype: datetime64[ns]

df

    S1          S2             S3
2020-12-31      naT            naT
2020-12-31      naT            naT
2020-12-31    2020-12-31       naT
2020-12-31    2020-12-31    2021-01-31

期望輸出:

   S1            S2             S3
2021-06-30      naT            naT
2021-06-30      naT            naT
2020-12-31    2021-06-30       naT
2020-12-31    2020-12-31    2021-07-31

使用.shift()查找行中的下一個單元格是否為 NaT,然后使用pd.DateOffset()為這些單元格添加額外的月份:

import pandas as pd
from io import StringIO

text = """
S1            S2             S3
2020-12-31    naT            naT
2020-12-31    naT            naT
2020-12-31    2020-12-31     naT
2020-12-31    2020-12-31     2021-01-31
"""

df = pd.read_csv(StringIO(text), header=0, sep='\s+')
df = df.apply(pd.to_datetime, errors='coerce')

# find in which cells the next value is na
next_value_in_row_na = df.shift(-1, axis=1).isna()

# for each cell where the next value is na, try to add 6 months
df = df.mask(next_value_in_row_na, df + pd.DateOffset(months=6))

結果數據框:

    S1          S2          S3
0   2021-06-30  NaT         NaT
1   2021-06-30  NaT         NaT
2   2020-12-31  2021-06-30  NaT
3   2020-12-31  2020-12-31  2021-07-31

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM