Python 使用数据帧的列值对多索引数据帧的行进行索引
如何为多索引数据帧的行编制索引Python 使用数据帧的列值对多索引数据帧的行进行索引,python,pandas,Python,Pandas,如何为多索引数据帧的行编制索引 import pandas as pd import numpy as np np.random.seed(0) tuples = list(zip(*[['bar', 'bar', 'baz', 'baz'],['one', 'two', 'one', 'two']])) idx = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) df = pd.DataFrame(np.random.r
import pandas as pd
import numpy as np
np.random.seed(0)
tuples = list(zip(*[['bar', 'bar', 'baz', 'baz'],['one', 'two', 'one', 'two']]))
idx = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(4, 2), index=idx, columns=['A', 'B'])
print(df)
A B
first second
bar one 1.764052 0.400157
two 0.978738 2.240893
baz one 1.867558 -0.977278
two 0.950088 -0.151357
idxDf = pd.DataFrame({'first':['bar','baz'],'second':['one','two']})
print(idxDf)
first second
0 bar one
1 baz two
使用第二个数据帧的列
import pandas as pd
import numpy as np
np.random.seed(0)
tuples = list(zip(*[['bar', 'bar', 'baz', 'baz'],['one', 'two', 'one', 'two']]))
idx = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(4, 2), index=idx, columns=['A', 'B'])
print(df)
A B
first second
bar one 1.764052 0.400157
two 0.978738 2.240893
baz one 1.867558 -0.977278
two 0.950088 -0.151357
idxDf = pd.DataFrame({'first':['bar','baz'],'second':['one','two']})
print(idxDf)
first second
0 bar one
1 baz two
从而生成的数据帧是
first second
bar one 1.764052 0.400157
baz two 0.950088 -0.151357
?
显然,df[idxDf['first','second']]
不起作用 与和一起使用:
或:
或在合并之前
:
print (df.merge(idxDf.set_index(['first','second']),
left_index=True,
right_index=True))
A B
first second
bar one 1.764052 0.400157
baz two 0.950088 -0.151357