【发布时间】:2021-05-05 02:10:35
【问题描述】:
我有一个多索引数据框,其中包含“bar”和“baz”行,并且每一行都有“one”和“two”行。我现在想在每行“bar”和 foo”中添加一行“三”。
有没有优雅的方法来做到这一点?
例如:
import pandas as pd
import numpy as np
arrays = [["bar", "bar", "baz", "baz"],
["one", "two", "one", "two"]]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"])
df = pd.DataFrame(np.random.randn(3, 4), index=["A", "B", "C"], columns=index)
In [38]: df
Out[38]:
first bar baz
second one two one two
A 0.357392 -1.880279 0.099014 1.354570
B 0.474572 0.442074 -1.173530 -1.362059
C -0.980140 -0.173440 -1.490654 -0.539123
我想要这样的东西:
first bar baz
second one two three one two three
A -0.096890 0.012150 nan -0.749569 -0.965033 nan
B -0.854206 0.118473 nan 0.263058 -0.025849 nan
C -0.688007 -0.258569 nan 0.127305 -0.955044 nan
【问题讨论】:
标签: python pandas dataframe multi-index