根据 pandas 列日期重复行值[已关闭]

问题描述 投票:0回答:1

我有一个与此类似的 pandas 数据框:

我想重复上一年到每年 12 月的值,如下所示:

我怎样才能用Python做到这一点?

python pandas dataframe date repeat
1个回答
0
投票

¡你好!

您可以创建“new_f_corr”列,其所有行中都没有值,除了与每年 12 月对应的行之外,在这些情况下,您可以从“f_corr”列复制值。然后,您可以使用“pandas.DataFrame.ffill”,它将最后一个有效观察传播到下一个有效观察。您可以参考“ffill”方法的文档here

这是适合您情况的代码:

# Create a new column with the same values as 'f_corr'
df['new_f_corr'] = df['df_corr']

# Identify the December rows and shift their 'f_corr' values down to repeat for the next year
df.loc[df['date'].dt.month != 12, 'new_f_corr'] = None
df['new_f_corr'] = df['new_f_corr'].ffill()

我假设您的日期存储为日期时间对象。

致以诚挚的问候。

© www.soinside.com 2019 - 2024. All rights reserved.