考虑这个数据集:
data_dict = {'ind' : [1, 2, 3, 4], 'location' : [301, 301, 302, 303], 'ind_var' : [4, 8, 10, 15], 'loc_var' : [1, 1, 7, 3]}
df = pd.DataFrame(data_dict)
df_indexed = df.set_index(['ind', 'location'])
df_indexed
看起来像
ind_var loc_var
ind location
1 301 4 1
2 301 8 1
3 302 10 7
4 303 15 3
ind_var 是一个随着个体变化而变化的变量,loc_var 是一个随着位置变化而变化的变量。(我还有一个变量是随着个体和位置同时变化的,但为了简化演示,我将其省略。)
我需要将数据转换为每个个体索引包含所有可能的位置。我可以这样重新索引(仅显示个体1到3):
new_shape = [(1, 301), (1, 302), (1, 303), (2, 301), (2, 302), (2, 303), (3, 301), (3, 302), (3, 303)]
idx = pd.Index(new_shape)
df2 = df_indexed.reindex(idx, method = None)
df2.index.names = ['id', 'location']
这提供了
ind_var loc_var
id location
1 301 4 1
302 NaN NaN
303 NaN NaN
2 301 8 1
302 NaN NaN
303 NaN NaN
3 301 NaN NaN
302 10 7
303 NaN NaN
但我需要一种方法来填补缺失的值,以便获得:
ind_var loc_var
id location
1 301 4 1
302 4 7
303 4 3
2 301 8 1
302 8 7
303 8 3
3 301 10 1
302 10 7
303 10 3
我尝试了两种不同的方法,但都没有成功:
1)使用loc_dict = {301:1,302:7,303:3}替换loc_var,以及ind_dict = {1:4,2:8,3:10,4:15}替换ind_var
2)使用groupby方法。
# First reset index
df_non_indexed = df2.reset_index()
df_non_indexed['loc_var'] = df_non_indexed.groupby(['location'])['loc_var'].transform(lambda x: x.fillna(method='ffill'))
这几乎有效,但只能进行向前(或向后)填充。一定有一种非常简单的方法来完成此操作,但我还没有想出来!感谢您的时间。
注:这与我的问题从宽到长的重塑有关。我采取了不同的方法,并简化了希望这个更容易理解。
[{'301':(4,1), '302':(nan, nan), '303':(nan,nan)}, {'301':...}
等。如果您使用此字典进行填充,提取所需的数据字典会更容易吗?很抱歉,我不熟悉Pandas。 - A.Wan