python - Pandas 创建完美面板数据,根据条件追加空行
问题描述
如果满足两个条件,我正在寻找一种将空行附加到数据框的方法。条件是,如果在特定年份未找到索引 ID,则代码将添加一个空行,该行具有索引“ID”和年份,但其他列为空。最终目的是创建一个完美的面板数据集,其中每个观察都表示 7 次(基于年份),尽管可能有来自某些观察的数据,例如 1 次或 3 次(这不是恒定的,而是会不时变化)。除了索引“ID”和年份之外,这些缺失的数据行将是空的。
这是我的数据框 all_data 当前的示例:
ID Year Data1 Data2
345 2010 3 2
345 2011 1 4
345 2012 5 2
345 2013 3 1
345 2014 3 1
345 2015 3 1
345 2016 3 1
123 2010 1 1
123 2012 0 2
123 2016 0 2
这是我正在寻找的一个例子。
ID Year Data1 Data2
345 2010 3 2
345 2011 1 4
345 2012 5 2
345 2013 3 1
345 2014 3 1
345 2015 3 1
345 2016 3 1
123 2010 1 1
123 2011
123 2012 0 2
123 2013
123 2014
123 2015
123 2016 0 2
我有 200 多个观察值和 20 个数据列,因此手动执行此操作需要太多时间。这是我尝试过的,但它不起作用。它返回相同的数据框并且不添加任何空行。“缺失”是一个列表,其中包含可以从 all_data 数据帧中找到的每个唯一 ID。
missing = ['345', '123']
sub_dfs = []
for year in [ 2010, 2011, 2012, 2013, 2014, 2015, 2016 ]:
sub_df = all_data.loc[ all_data[ 'Year' ] == year ].copy()
if( year == 2010):
sub_df.set_index( 'ID', inplace=True)
sub_df.reindex(sub_df.index.union(missing))
if (year == 2011):
sub_df.set_index('ID', inplace=True)
sub_df.reindex(sub_df.index.union(missing))
if (year == 2012):
sub_df.set_index('ID', inplace=True)
sub_df.reindex(sub_df.index.union(missing))
if (year == 2013):
sub_df.set_index('ID', inplace=True)
sub_df.reindex(sub_df.index.union(missing))
if (year == 2014):
sub_df.set_index('ID', inplace=True)
sub_df.reindex(sub_df.index.union(missing))
if (year == 2015):
sub_df.set_index('ID', inplace=True)
sub_df.reindex(sub_df.index.union(missing))
if (year == 2016):
sub_df.set_index('ID', inplace=True)
sub_df.reindex(sub_df.index.union(missing))
sub_dfs.append(sub_df)
new_data = pd.concat(sub_dfs)
预先感谢您的帮助!
解决方案
使用reindex
by Multiindex
created by MultiIndex.from_product
by 的所有unique
值ID
with np.arange
by minimum 和 maximum year
s:
mux = pd.MultiIndex.from_product([df['ID'].unique(),
np.arange(df['Year'].min(), df['Year'].max() + 1)],
names=['ID','Year'])
df = df.set_index(['ID','Year']).reindex(mux).reset_index()
print (df)
ID Year Data1 Data2
0 345 2010 3.0 2.0
1 345 2011 1.0 4.0
2 345 2012 5.0 2.0
3 345 2013 3.0 1.0
4 345 2014 3.0 1.0
5 345 2015 3.0 1.0
6 345 2016 3.0 1.0
7 123 2010 1.0 1.0
8 123 2011 NaN NaN
9 123 2012 0.0 2.0
10 123 2013 NaN NaN
11 123 2014 NaN NaN
12 123 2015 NaN NaN
13 123 2016 0.0 2.0
推荐阅读
- python - 动态更新 Dash Plotly 中的标题
- java - Spring Integration JPA:有没有办法在 IntegrationFlows Jpa.inboundAdapter 中传递 JpaRepository 而不是 EntityManagerFactory?
- flutter - 如何使用 NULL Safety 重置飞镖/颤振中的文件类型变量?
- php - Laravel - 我可以让我通过 Laravel Passport 登录 Facebook 吗?
- java - 如何解决队列多消费并发问题?
- android - 如何在 Android Jetpack Compose 中结合使用 LazyColumn stickyHeader 和 Paging?
- curl - 如何将提交更改从 GitLab 发送到团队
- latex - TikZ - 带箭头的弧线
- angular - 仅构建角度应用程序的特定模块
- python - Python 3 flask cairo 在 Apple M1 硅片上封装错误的架构