1

У меня есть следующий DataFarme

    Item    Store   Year    Week    Qnty_y  Date        is_season
 0  2178    5001    2017    43  0.0 2017-10-28             0
 1  2178    5001    2017    46  0.0 2017-11-19             0
 2  2178    5001    2017    47  1.0 2017-11-21             1
 3  2178    5001    2017    47  1.0 2017-11-24             1
 4  2178    5001    2017    47  1.0 2017-11-20             1

мне нужно получить следующий DataFrame

     Item   Store   Year    Week    Qnty_y  Date        is_season
 0  2178    5001    2017    43  0.0 2017-10-28             0
 1  2178    5001    2017    46  0.0 2017-11-19             0
 2  2178    5001    2017    47  1.0 2017-11-21     2017-11-21
 3  2178    5001    2017    47  1.0 2017-11-24             1
 4  2178    5001    2017    47  1.0 2017-11-20     2017-11-20

т.е. для каждого Item в поле is_season должна перенестись дата (Date) из той же строки, по условию первого вхождения единицы в поле is_season и последнего вхождения единицы в поле is_season

пробовала через

mask_1= df.eval('is_season == 1')
df.loc[mask_1, "Is_season"] \
= np.where(df.loc[mask_1].groupby("Item")['is_season'].first(), df.loc['Date'], 0)

df.loc[mask_1, "Is_season"] \
= np.where(df.loc[mask_1].groupby("Item")['is_season'].last(), df.loc['Date'], 0)

не помогает

0

1 ответ 1

5

Можно сделать так:

idx = (df.query("is_season == 1")
         .index
         .to_series()
         .groupby(df["Item"])
         .agg(["first", "last"])
         .stack()
         .to_numpy())
df.loc[idx, "is_season"] = df.loc[idx, "Date"]

или так:

idx = (np.concatenate(df.query("is_season == 1")
                        .groupby("Item")
                        ["is_season"]
                        .apply(lambda x: x.index[[0,-1]].values)
         .values))
df.loc[idx, "is_season"] = df.loc[idx, "Date"]

результат:

In [74]: df
Out[74]:
   Item  Store  Year  Week  Qnty_y        Date   is_season
0  2178   5001  2017    43     0.0  2017-10-28           0
1  2178   5001  2017    46     0.0  2017-11-19           0
2  2178   5001  2017    47     1.0  2017-11-21  2017-11-21
3  2178   5001  2017    47     1.0  2017-11-24           1
4  2178   5001  2017    47     1.0  2017-11-20  2017-11-20
5  2222   5111  2017    43     0.0  2017-10-28           0
6  2222   5111  2017    47     1.0  2017-11-21  2017-11-21
7  2222   5111  2017    47     1.0  2017-11-20  2017-11-20

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.