Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
For loop solo almacena el último valor en la columna

Estoy tratando de obtener el número de semana dado una fecha y luego agregar ese número de semana a la fila correspondiente en un marco de datos de pandas/python.

Cuando ejecuto un bucle for, solo almacena el último valor calculado en lugar de registrar cada valor.

He intentado .append pero no he podido hacer que nada funcione.

 import datetime from datetime import date for i in df.index: week_number = date(df.year[i],df.month[i],df.day[i]).isocalendar() df['week'] = (week_number[1]) Expected values: day month year week 8 12 2021 49 19 12 2021 50 26 12 2021 51 Values I'm getting: day month year week 8 12 2021 51 19 12 2021 51 26 12 2021 51
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Debe volver a asignarlo en la posición correcta correspondiente, i . Usando loc , debería ayudar:

 for i in df.index: week_number = date(df.year[i],df.month[i],df.day[i]).isocalendar() df.loc[i,'week'] = (week_number[1])

imprime hacia atrás:

 print(df) day month year week 0 8 12 2021 49 1 19 12 2021 50 2 26 12 2021 51
over 4 years ago · Santiago Trujillo Report

0

Simplemente puede usar el método .apply de Pandas para convertirlo en una sola línea:

 df["week"] = df.apply(lambda x: date(x.year, x.month, x.day).isocalendar()[1], axis=1)
over 4 years ago · Santiago Trujillo Report

0

Puede usar esto, sin usar apply , que es lento:

 df['week'] = pd.to_datetime(df['year'].astype(str) + '-' + df['month'].astype(str) + '-' + df['day'].astype(str)).dt.isocalendar().week
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!