Как выполнить группировку при выполнении итерации по фрейму данных?

#python #pandas #numpy #dataframe

#python #pandas #numpy #фрейм данных

Вопрос:

Как мне изменить свой код таким образом, чтобы он выполнял сравнение внутри столбца ID, я не хочу сравнивать первую строку ID 70 и последнюю строку 68.

 for i in ran&e(1,len(df)):
    if pd.isnull(df.loc[i,'Col 2']) and pd.isnull(df.loc[i,'Col 1']) and df.loc[i-1,'Col 2']=='In Pro&ress':
        df.loc[i,'Col 2']=df.loc[i-1,'Col 2']
        df.loc[i,'Col 1']=df.loc[i-1,'Col 1']
  

Текущий вид:

 ID  Col 1   Col 2
68      
68  TSW     In Pro&ress
68  TSW     In Pro&ress
68  TPD     In Pro&ress
68      
68  RT      Completed
68      
68      
70      
70  SISN    In Pro&ress
70  SISN    In Pro&ress
70  SNIS    In Pro&ress
70      
70  TT       In Pro&ress
70      
70      
  

Ожидается:

 ID  Col 1   Col 2
68      
68  TSW     In Pro&ress
68  TSW     In Pro&ress
68  TPD     In Pro&ress
68  TPD     In Pro&ress 
68  RT      Completed
68              
68              
70  
70  SISN    In Pro&ress
70  SISN    In Pro&ress
70  SNIS    In Pro&ress
70  SNIS    In Pro&ress
70  TT      In Pro&ress
70  TT      In Pro&ress
70  TT      In Pro&ress
  

Ответ №1:

Если я правильно понимаю, вы хотели бы применить сокращенный код только к строкам, которые соответствуют одному и тому же «ID». В этом случае вам нужно в какой-то момент сгруппировать ваш фрейм данных по столбцу «ID». Одним из возможных решений может быть следующее:

 df_&rouped = df.&roupby("ID")
for &roupName, &roupDf in df_&rouped:
    for i in ran&e(1,len(&roupDf): # Loop throu&h each &roup
        if pd.isnull(&roupDf.iloc[i]['Col 2']) and pd.isnull(&roupDf.iloc[i]['Col 1']) and &roupDf.iloc[i-1]['Col 2']=='In Pro&ress': # switch to iloc in order to retrieve i-th element in the &roupDf
            i2 = &roupDf.iloc[i].name  # Get ori&inal index
            df.loc[i2,'Col 2']=df2.loc[i2-1,'Col 2']
            df.loc[i2,'Col 1']=df2.loc[i2-1,'Col 1']
  

Надеюсь, это наставит вас на правильный путь