填充数据框列Python中的缺失值

时间:2018-11-11 00:14:32

标签: python python-3.x pandas dataframe

我的数据分为4列,如下所示:

State       Year        Month        Value
AK          2010         1             10
AK          2010         3             20
AK          2011         1             28
AK          2011         5             29
AK          2011         12            31
.
.
TX          2010         2             10
TX          2010         3             11
TX          2010         4             20
TX          2010         12            22
TX          2011         4             30
TX          2011         7             33
.
.

我想用与 Year 相同的以前的 Values 重复来填充丢失的 Months ,因为它们只是我的累计金额已添加到一起。

月份不一定总是从第1个月开始,并且有时可能会丢失整整一年,所以我需要解决这个问题。

即:TX可以从2011年的第4个月开始,等等...

所需的输出如下:

State       Year        Month        Value
AK          2010         1             10
AK          2010         2             10
AK          2010         3             20
AK          2010         4             20
AK          2010         5             20
.
.
AK          2010         12            20
AK          2011         1             28
AK          2011         2             28
.
.
TX          2010         1             9
TX          2010         2             10
TX          2010         3             11
TX          2010         4             20
TX          2010         5             20
.
.
TX          2010         12            22

1 个答案:

答案 0 :(得分:1)

一种解决方案是使用Categorical Data

# convert Month to categorical with 1-12 range
df['Month'] = pd.Categorical(df['Month'], categories=range(1, 13))

# groupby to give Cartesian product for categorical columns
df = df.groupby(['State', 'Year', 'Month']).first().reset_index()

# forward fill by group
df['Value'] = df.groupby('State')['Value'].ffill()

该解决方案假定2010年12月的数据可以溢出到特定状态的2011年1月的空数据。

相关问题