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
1 Answer
Reset to default 0Build 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())
版权声明:本文标题:python - Looping through a dataframe column to replace NaN values with values that aren't null: - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744577794a2613733.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论