admin管理员组

文章数量:1390478

The three columns on the left are day month, and year. I am trying to fill in NaN values in the last column which I am calling 'C'. For each week of each month there is one non-empty value in the last column, and I would like to assign the NaN values with the non-empty value.

So far I have tried doing it with the first week with the following code:

for year in range(2013, 2023):
  for month in range(1, 13):
    for day in range(1, 8):
      df.loc[pd.isnull(df['C']), 'C'] = df.loc[(df['year'] == year) & (df['month'] == month) & (df['day'] == 3), 'C']

The three columns on the left are day month, and year. I am trying to fill in NaN values in the last column which I am calling 'C'. For each week of each month there is one non-empty value in the last column, and I would like to assign the NaN values with the non-empty value.

So far I have tried doing it with the first week with the following code:

for year in range(2013, 2023):
  for month in range(1, 13):
    for day in range(1, 8):
      df.loc[pd.isnull(df['C']), 'C'] = df.loc[(df['year'] == year) & (df['month'] == month) & (df['day'] == 3), 'C']
Share Improve this question edited Mar 17 at 20:48 CcmU 1,03614 silver badges31 bronze badges asked Mar 17 at 5:53 Hashem KherfiHashem Kherfi 1
Add a comment  | 

1 Answer 1

Reset to default 0

Build a column week and then use grouping over the columns year, month and week and use .ffill and .bfill:

df['week'] = df['day'].apply(lambda x: (x - 1) // 7 + 1)  # Assign week numbers
df['C'] = df.groupby(['year', 'month', 'week'])['C'].transform(lambda x: x.ffill().bfill())

本文标签: pythonLooping through a dataframe column to replace NaN values with values that aren39t nullStack Overflow