【发布时间】:2019-12-07 05:27:57
【问题描述】:
arrays = [['indcator_1', 'indcator_1', 'indcator_2', 'indcator_2', 'indcator_3', 'indcator_3', 'indcator_4', 'indcator_4'], ['2018', '2019', '2018', '2019', '2018', '2019', '2018', '2019']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['indicators', 'state'])
df = pd.DataFrame(np.random.randn(3, 8), index=['AZ', 'CA', 'IL'], columns=index)
df
Out[5]:
indicators indcator_1 indcator_2 indcator_3 \
state 2018 2019 2018 2019 2018 2019
AZ 0.823890 0.165838 -1.207324 0.991570 0.424288 -0.697368
CA 0.323375 -1.301540 1.245174 -0.542040 -0.305037 -0.148536
IL 0.283575 0.095836 0.542553 -0.179618 1.989065 0.914899
indicators indcator_4
state 2018 2019
AZ -1.544907 -0.286541
CA 1.168241 1.702455
IL 0.524246 2.031239
我想像这样重塑它:
有没有办法做到这一点?我在任何地方都找不到针对这种特定情况的解决方案。
抱歉,问题的介绍很糟糕。我是新来的。
感谢您的帮助!
【问题讨论】:
-
欢迎来到 SO。请查看How to Ask 并创建一个minimal reproducible example,这意味着没有代码图片,建议您在发布之前阅读的内容中明确说明了这一点。跨度>
-
那些 DF 小到可以粘贴文本。图片是个坏主意,会让你被否决。
-
只需写下可以生成它们的代码即可
-
谢谢大家的指点。我已经相应地编辑了这个问题。下次会记住的:)
标签: python pandas pivot multi-index melt