【问题标题】:For loop is only storing the last value in columFor循环仅存储列中的最后一个值
【发布时间】:2022-01-25 21:00:56
【问题描述】:

我正在尝试提取给定日期的周数,然后将该周数添加到 pandas/python 数据框中的相应行。

当我运行 for 循环时,它只存储最后计算的值,而不是记录每个值。

我尝试了 .append,但没有任何效果。

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  

【问题讨论】:

  • 你认为df['week'] = (week_number[1]) 在做什么?为什么你认为输出会不同?

标签: python pandas


【解决方案1】:

您需要将其分配回正确的对应位置i。使用loc,应该会有所帮助:

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])

打印回来:

print(df)

   day  month  year  week
0    8     12  2021    49
1   19     12  2021    50
2   26     12  2021    51

【讨论】:

    【解决方案2】:

    您可以简单地使用 Pandas .apply 方法使其成为单行:

    df["week"] = df.apply(lambda x: date(x.year, x.month, x.day).isocalendar()[1], axis=1)
    

    【讨论】:

      【解决方案3】:

      您可以使用它,而无需使用很慢的apply

      df['week'] = pd.to_datetime(df['year'].astype(str) + '-' + df['month'].astype(str) + '-' + df['day'].astype(str)).dt.isocalendar().week
      

      【讨论】:

        猜你喜欢
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-28
        • 1970-01-01
        • 2019-05-15
        • 1970-01-01
        相关资源
        最近更新 更多