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

标签 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
.
.

我想用同一年份的先前的重复项来填充缺失的月份,因为它们只是我的累积总和。已经加在一起了。

月份并不总是从第 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

最佳答案

一种解决方案是使用 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 月的空数据。

关于python - 填充数据框列Python中的缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53244687/

相关文章:

python - 在析构函数中从其类的字典中删除实例吗?

python - 用 1 替换列中的非 Null 值

python - 删除 tf.dataset 管道中输入字符串的重音

python - 并行修改切片中的 3D numpy 数组

python - Keras 嵌入层输入形状的困惑

python - 如何在Python中实现向前兼容的字符串文字?

python - Zope 安装到错误的版本(easy_install 和 pip)

python - 64 位 Python 中的 32 位 float 学运算

python - 在groupby之后访问pandas中的分层列

python - 将多个 CSV 文件读取到 DataFrames 并以其原始文件名命名