Python 将数据排序到多索引数据帧中
如何将数据帧中的数据排序到对索引和列都使用多索引的数据帧中 例如,从以下内容转换:Python 将数据排序到多索引数据帧中,python,pandas,Python,Pandas,如何将数据帧中的数据排序到对索引和列都使用多索引的数据帧中 例如,从以下内容转换: 0 1 2 3 4 0 foo two A 2.30 0.01 1 foo one A 4.12 0.13 2 bar two B 9.89 3.66 3 foo one A 2.11 9.48 4 bar two A 1.07 5.55 为此: A B
0 1 2 3 4
0 foo two A 2.30 0.01
1 foo one A 4.12 0.13
2 bar two B 9.89 3.66
3 foo one A 2.11 9.48
4 bar two A 1.07 5.55
为此:
A B
1 2 1 2
foo one 2.11 9.48 NaN NaN
two 2.3 0.01 NaN NaN
bar one NaN NaN NaN NaN
two 1.07 5.55 9.89 3.66
目前,我正在迭代df1
中的每一行,并更新df2
中的值,但我想要一种比这更有效的方法:
for index, row in df1.iterrows():
df2.loc[(row[0], row[1]), row[2]] = list(row[3:])
您可以使用:
def f(x):
return pd.DataFrame({'a':x.values.ravel()}).rename(lambda x: x + 1)
df = df.groupby([0,1,2])[3,4].apply(f)['a'].unstack([2,3]).sort_index(level=0, axis=1)
df = df.rename_axis((None, None),axis=1).reindex(pd.MultiIndex.from_product(df.index.levels))
print (df)
A B
1 2 3 4 1 2
bar one NaN NaN NaN NaN NaN NaN
two 1.07 5.55 NaN NaN 9.89 3.66
foo one 4.12 0.13 2.11 9.48 NaN NaN
two 2.30 0.01 NaN NaN NaN NaN
说明:
DataFrame
的自定义函数,还应增加start from1
2
),并将缺少的类别添加到索引by and中的多索引
你能简单解释一下这是如何提高性能的吗?@user2970608-不确定是否理解,最后的
解释是不够的?我的意思是为什么会这样faster@user2970608-因为iterrows
显然很少使用,因为非常慢-检查。