python - 将数据排序到多索引数据框中
问题描述
如何将 DataFrame 中的数据排序到对索引和列都使用 MultiIndex 的 DataFrame 中?
例如,从此转换:
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
说明:
对于前 3 列
apply
自定义函数的每个组DataFrame
,还增加索引值以从1
重塑并按列
unstack
排序Multiindex
sort_index
删除列名(
2
在左角)并将缺少的类别添加到MultiIndex
索引reindex
中MultiIndex.from_product
推荐阅读
- python - 用于生物医学命名实体识别 (NER) 的 Scispacy
- java - 使用多线程将元素添加到 ArrayList 时,有时会给出 ConcurrentModificationException 有时不会?
- javascript - “类型字符串的参数不能分配给自定义类型的参数”的难看问题
- python - Python中的两个简单的if-else代码,它们不应该返回相同的值吗?为什么每个人都会返回其他东西
- c# - 如何使用 Xamarin Forms 为 GTK 和 WPF 显示 gif 或 mp4
- cordova - 让 Cordova 在 CI/CD 环境中构建更高效
- javascript - JavaScript window.print() 给了我一个空白页
- java - 自定义 swagger-ui.html 中的内容
- c# - 如何在文本框和列表框/绑定列表框之间进行双向绑定?
- sql - 计算月份之间的总差