【问题标题】:Creating a balanced panel dataset [closed]创建一个平衡的面板数据集[关闭]
【发布时间】:2021-05-24 21:46:38
【问题描述】:

我有一个数据集

id  year      sales
1    2000      10
2    2000      10
2    2001      20
2    2002      30

我想创建一个平衡面板,以便获得以下信息:

id  year      sales
1    2000      10
1    2001      NA
1    2002      NA
2    2000      10
2    2001      20
2    2002      30

我尝试了以下代码:

df_balanced = (df.set_index('year',append=True).reindex(pd.MultiIndex.from_product([df.index.unique(),range(df.year.min(),df.year.max()+1)],names['id','year'])).reset_index(level=1))

但我没有得到想要的输出。

【问题讨论】:

  • 请提供预期的minimal, reproducible example (MRE)。我们应该能够复制并粘贴您的代码的连续块,执行该文件,并重现您的问题以及跟踪问题点的输出。这让我们可以根据您的测试数据和所需的输出来测试我们的建议。显示中间结果与您的预期不同的地方。
  • include a minimal data frame 作为您的 MRE 的一部分。

标签: python pandas dataframe panel balance


【解决方案1】:
idx = pd.MultiIndex.from_product(
    [df.id.unique(), df.year.unique()], names=["id", "year"]
)
df = df.set_index(["id", "year"]).reindex(idx).reset_index()
print(df)

打印:

   id  year  sales
0   1  2000   10.0
1   1  2001    NaN
2   1  2002    NaN
3   2  2000   10.0
4   2  2001   20.0
5   2  2002   30.0

【讨论】:

  • 嗨安德烈,谢谢你的帖子!我收到以下错误:cannot handle a non-unique multi-index!
  • @Jui 您可能在“id”、“year”列中具有相同值的行。之前可以df = df.drop_duplicates(subset=["id", "year"])
  • 非常感谢!
猜你喜欢
  • 2018-07-28
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
相关资源
最近更新 更多