python - Pandas 根据值插入行并用 0 填充

标签 python pandas nan fill reindex

我有以下数据框,具有以下值。 我想插入行,以便为每个人(Toby、Jane、David)以及 2020 年的每个月添加一行。 如果 x 或 y 没有值,则填充 0。

    ID  Name    Date        x   y
0   001 Toby    2020-01-01  15  NaN
1   001 Toby    2020-02-01  12  7
2   001 Toby    2020-05-01  7   1
3   001 Toby    2020-07-01  NaN 1
4   002 Jane    2020-11-01  20  1
5   002 Jane    2020-12-01  21  10
6   003 David   2020-07-01  -3  2

生成的数据框应有 36 行,每个人 12 行。

ID  Name        Date        x   y
0   001 Toby    2020-01-01  15  0
1   001 Toby    2020-02-01  12  7
2   001 Toby    2020-03-01  0   0
3   001 Toby    2020-04-01  0   0
4   001 Toby    2020-05-01  7   1
5   001 Toby    2020-06-01  0   0
6   001 Toby    2020-07-01  0   1
7   001 Toby    2020-08-01  0   0
8   001 Toby    2020-09-01  0   0
9   001 Toby    2020-10-01  0   0
10  001 Toby    2020-11-01  0   0
11  001 Toby    2020-12-01  0   0
12  002 Jane    2020-01-01  0   0
13  002 Jane    2020-02-01  0   0
14  002 Jane    2020-03-01  0   0
15  002 Jane    2020-04-01  0   0
16  002 Jane    2020-05-01  0   0
17  002 Jane    2020-06-01  0   0
18  002 Jane    2020-07-01  0   0
19  002 Jane    2020-08-01  0   0
20  002 Jane    2020-09-01  0   0
21  002 Jane    2020-10-01  0   0
22  002 Jane    2020-11-01  20  1
23  002 Jane    2020-12-01  21  10
24  003 David   2020-01-01  0   0
25  003 David   2020-02-01  0   0
26  003 David   2020-03-01  0   0
27  003 David   2020-04-01  0   0
28  003 David   2020-05-01  0   0
29  003 David   2020-06-01  0   0
30  003 David   2020-07-01  -3  2
31  003 David   2020-08-01  0   0
32  003 David   2020-09-01  0   0
33  003 David   2020-10-01  0   0
34  003 David   2020-11-01  0   0
35  003 David   2020-12-01  0   0

我研究了reindex,并设法使其在单个系列上工作。但我还没有找到一种方法来在数据帧上动态生成行,然后填充缺失的值。

如有任何帮助,我们将不胜感激。

最佳答案

您可以使用重新索引来达到以下目的:

# list of the desired dates
# make sure that it has the same type with `Date` in your data
# here I assume strings
dates = pd.Series([f'2020-{x}-01' for x in range(1,13)]), name='Date')

(df.set_index(['Date']).groupby(['ID','Name'])
   .apply(lambda x: x.drop(['ID', 'Name'],axis=1).reindex(dates).fillna(0))
   .reset_index()
)

关于python - Pandas 根据值插入行并用 0 填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61916996/

相关文章:

python - 为什么 numpy 方法可以在 pandas 数据帧上工作?

python - 数据实验室 : How to export Big Query standard SQL query to dataframe?

python - 如何在 Pandas 中用滚动平均值填充南值

python - Alembic 自动生成空的 Flask-SQLAlchemy 迁移

python - 如何使用 Python 和 BeautifulSoup 抓取多个 google 页面

python - 索引错误: index 6 is out of bounds for axis 0 with size 2

python - Pandas/Matplotlib 条形图按条件颜色

javascript - 即使使用 parseInt 转换计算后我仍然得到 NaN

Java HashMap<Integer, Double> 插入 NaN

python - 确定2个列表是否具有相同的元素,而不管顺序如何?